選擇所要上傳的文件css
upload.jsphtml
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <%//引入struts2標籤 %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <table align="center" width="50%"> <tr> <td> <% // <s:fielderror cssStyle="color:red"/>%> </td> </tr> </table> <s:form action="upload" theme="simple" enctype="multipart/form-data"> <%//設置form表單的enctype屬性爲multipart/form-data %> <table align="center" width="50%" border="1"> <tr> <td>file</td> <td><s:file name="file"></s:file> </tr> <tr> <td><s:submit value="submit"></s:submit></td> <td><s:reset value="reset"></s:reset></td> </tr> </table> </s:form> </body> </html>
實現文件上傳功能java
UploadAction.javaapache
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; public class UploadAction extends ActionSupport{ private File file; //建立file屬性 private String fileFileName; //建立fileFileName屬性,表明文件名稱 private String fileContentType; //建立fileContentType屬性,表明文件類型 public File getFile() { return file; } public void setFile(File file) { this.file = file; } public String getFileFileName() { return fileFileName; } public void setFileFileName(String fileFileName) { this.fileFileName = fileFileName; } public String getFileContentType() { return fileContentType; } public void setFileContentType(String fileContentType) { this.fileContentType = fileContentType; } public String execute() throws Exception { InputStream is = new FileInputStream(file); String root = "E:/shang"; //設置上傳的路徑 File destFile = new File(root, this.getFileFileName()); //destFile文件:輸出流的目的文件 OutputStream os = new FileOutputStream(destFile); //os文件:關於destFile文件的輸出流 byte[] buffer = new byte[400]; //buffer字節數組:實現輸入流與輸出流的轉換 int length = 0; while ((length = is.read(buffer)) > 0) { os.write(buffer, 0, length); } is.close(); os.close(); return SUCCESS; } }
配置struts.xml 文件數組
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <!-- 聲明包 --> <package name="myPackage" extends="struts-default"> <!-- 訪問首頁 --> <action name="upload" class="com.lyq.upload.UploadAction"> <result>uploadResult.jsp</result> </action> </package> </struts>