Struts檔案上傳,struts2檔案上傳
用兩個包:一個是commons-fileupload-1.3.2.jar,另一個是commons-io-2.2.jar
jsp介面:
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%><!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><form action="Shangchuan_add" method="post" enctype="multipart/form-data"><input type="file" name="file"><br><br><input type="submit" value="submit" ></form></body></html>
做Action。
三個成員:1.File file上傳的檔案 2.String fileFileName屬性名稱3.String fileContentType屬性名稱
org.apache.commons.io.FileUtils.copyFile很簡單。
sturts.xml設定檔,可在裡面添加常量,修改檔案上傳的大小限制。就可以上傳大檔案了
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"><struts> <constant name="struts.enable.DynamicMethodInvocation" value="true" /> <constant name="struts.devMode" value="true" /> <constant name="struts.i18n.encoding" value="UTF-8"></constant> <constant name="struts.ui.theme" value="simple"></constant> <constant name="struts.multipart.maxSize" value="20971520"></constant><!-- 修改限制上傳檔案大小,預設是2097152 --> <package name="default" namespace="/" extends="struts-default"> <action name="*_*" class="com.itnba.maya.controller.{1}Action" method="{2}"> <result> {1}_{2}.jsp </result> </action> </package> <include file="example.xml"/> <!-- Add packages here --></struts>
解決重新命名問題
package com.itnba.maya.controller;import java.io.File;import java.io.IOException;import java.text.SimpleDateFormat;import java.util.Date;import org.apache.commons.io.FileUtils;import com.opensymphony.xwork2.ActionSupport;public class ShangchuanAction extends ActionSupport { private File file; private String fileFileName;//上傳檔案的名字 private String fileContentType;//上傳檔案的格式 public File getFile() { return 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 void setFile(File file) { this.file = file; } public String input(){ return SUCCESS; } public String add() throws IOException{ //為了防止上傳檔案重名,在檔案前面加上目前時間 long l=System.currentTimeMillis(); Date date=new Date(l); SimpleDateFormat sdf= new SimpleDateFormat("yyyyMMddhhmmssSSS");//精確到毫秒 String pre=sdf.format(date); String fileName = pre+fileFileName; File destFile = new File("d:\\"+fileName);//放到哪裡的路徑+檔案名稱 FileUtils.copyFile(file, destFile); return SUCCESS; }}
上傳完成
*************************************************************************************
多個檔案同時上傳,三個成員定義成數組