struts2檔案上傳,設定臨時目錄和限制檔案大小 以及 批量上傳
阿新 • • 發佈:2019-02-08
在src下新建,struts.properties檔案,檔名是固定,用來更改一些預設配置。
可以在struts2的jar包下找到預設的配置檔案,一般不不去修改修改那個檔案。
struts.multipart.saveDir=d:/upload
struts.multipart.maxSize=9000000
struts2上傳檔案並不是我們想象的直接上傳那麼簡單。
需要先上傳到臨時檔案中,最後在移動到指定的目錄中。
批量上傳是這樣的,現在表單中把name設定為一樣的。
<form action="upload.action" method="post" enctype="multipart/form-data"> <input type="file" name="files"><br> <input type="file" name="files"><br> <input type="file" name="files"><br> <input type="submit" value="上傳"> </form>
然後在action中這樣處理
private List<File> files; //命名要一致!!
private List<String> filesFileName; //後兩個命名格式是固定的
private List<String> filesContentType;
剩下的就是遍歷了,各個擊破
public String execute() throws Exception { //放在了files檔案下 String path = ServletActionContext.getRequest().getRealPath("/files"); int n = files.size(); for(int i=0; i<n; i++){ InputStream is = new FileInputStream(files.get(i)); OutputStream os = new FileOutputStream(new File(path,filesFileName.get(i))); byte[] buffer = new byte[1024*10]; int length = 0; while( -1 != (length = is.read(buffer))){ os.write(buffer, 0, length); } is.close(); os.close(); } return SUCCESS; } }