struts實現文件的上傳,有三個部分:JSP頁面,Action,struts.xmlhtml
1.JSP頁面java
<s:file name="image" label="請選擇文件"></s:file> <s:submit value="上傳"></s:submit>
2.Action中服務器
//用於保存頁面file控件上傳的數據 private File image; //保存上傳文件的名稱 //格式必須是:頁面file控件的名稱再加上FileName的格式 private String imageFileName; //保存上傳文件的類型,如image、doc、zip等 //格式必須是:頁面file控件的名稱再加上FileContent的格式 private String imageContentType; public String execute() throws Exception { //獲取文件上傳後在服務器保存的位置 //注意要在Webcontent下建立 //images文件夾用於保存文件 String path= ServletActionContext.getServletContext() .getRealPath("/images"); //按照原文件名在images文件夾下構建文件 File file= new File(path+"//"+imageFileName); //利用commons-io包中的FileUtiles類實現文件上傳 FileUtils.copyFile(image, file); return SUCCESS; }
3.struts配置jsp
<struts> <!-- 設置上傳文件的臨時目錄 --> <constant name="struts.multipart.saveDir" value="e:\\temp"></constant> <!-- 設置上傳文件的大小 --> <constant name="struts.multipart.maxSize" value="2097152"></constant> <package name="file" extends="struts-default" namespace="/"> <action name="fileAction" class="com.action.FileAction"> <result name="success">/success.jsp</result> </action> </package> </struts>
分析:
文件上傳過程:在頁面點擊上傳以後,會在臨時目錄上會生成臨時文件(臨時文件的路徑在struts的配置文件中constant的struts.multipart.saveDir中設置,若是沒有設置,就是默認的Javax.servlet.context.tempDir;)
在Action中接收的image文件就是這個臨時文件。
在Action的execute方法中,路徑path是文件上傳到服務器上以後,該文件在服務器上的路徑,
這裏是經過ServletActionContext.getServletContext().getRealPath("/images")獲取images文件夾在服務器上的絕對路徑,
由於要把上傳的文件放在images文件夾下,因此path+fileName,就是文件的絕對路徑了;
而後使用new File(path+fileName)建立文件;
FileUtils.copyFile(image,file);把本地的臨時文件上傳到了服務器上。
spa