不得不說,struts2的文件上傳功能做的實在是太方便了,如果脫離struts2的文件上傳功能,單純使用servlet結合fileUpload工具包,1k1k的讀,1k1k的寫,那么struts2的文件上傳功能,簡直是把代碼量縮減的不止一點半點。
首先,文件上傳的表單必須是以下設置
1 <form action="XXX" method="post" enctype="multipart/form-data">
設置完畢之后,看一下servlet的post的方法的設置
1 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
2
3 request.setCharacterEncoding("utf-8");
4
5 // 首先需要確認,到底是不是文件上傳的請求,
6 boolean isMultipart = ServletFileUpload.isMultipartContent(request);
7
8 if (isMultipart) {
9 // 創建一個文件處理對象
10 ServletFileUpload upload = new ServletFileUpload();
11 InputStream is = null;
12 FileOutputStream os = null;
13 try {
14 // 解析請求中的所有元素
15 FileItemIterator iter = upload.getItemIterator(request);
16 while (iter.hasNext()) {
17 FileItemStream item = iter.next();
18 is = item.openStream();
19 //是否是表單域
20 if (item.isFormField()) {
21 //其他操作,保存參數等
22 } else {
23 //不是表單域則保存文件
24 String path = request.getSession().getServletContext().getRealPath("/");
25 path = path + "/upload/" + item.getName();
26 os = new FileOutputStream(path);
27 //流讀寫
28 byte[] buf = new byte[1024];
29 while(is.read(buf)>0){
30 os.write(buf);
31 }
32 }
33
34 }
35 } catch (FileUploadException e) {
36 e.printStackTrace();
37 } finally{
38 if (is != null) {
39 is.close();
40 }
41 if (os != null) {
42 os.close();
43 }
44 }
45 }
46 } 洋洋灑灑一大堆,struts2封裝了這些通用的處理,我們可以按照struts2的風格來獲取要上傳文件的對象,直接寫一個多文件上傳的例子吧
1 <%@ page language="java" contentType="text/html; charset=UTF-8"
2 pageEncoding="UTF-8"%>
3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
4 <html>
5 <head>
6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
7 <title>文件上傳</title>
8 </head>
9 <body>
10 <form action="FileUpload" method="post" enctype="multipart/form-data">
11 文件上傳測試:<br>
12 <input type="file" name="text"/><br>
13 <input type="file" name="text"/><br>
14 <input type="file" name="text"/><br>
15 <input type="submit" value="提交">
16 </form>
17 </body>
18 </html>
action為
1 package demo.fileUpload;
2
3 import java.io.File;
4 import java.io.IOException;
5
6 import org.apache.commons.io.FileUtils;
7 import org.apache.struts2.ServletActionContext;
8
9 public class FileUpload {
10
11 //文件接收數組,如果是單文件上傳,那就不需要定義數組了,定義單個文件對象就行
12 private File text[];
13 //對應的文件名,這里的文件名是“名字.后綴”的形式,這個屬性的命名需要是“文件屬性的名字”+FileName。
14 private String[] textFileName;
15 //對應的文件類型,是文件的真實類型,比如“text/plain”,這個屬性的命名需要是“文件屬性的名字”+ContentType
16 private String[] textContentType;
17
18 public String execute() throws IOException{
19
20 String dir = "";
21 File file = null;
22
23 for (int i = 0; i < text.length; i++) {
24 //創建要新建的文件位置
25 dir = ServletActionContext.getServletContext().getRealPath("/") + "/upload/" + textFileName[i];
26 file = new File(dir);
27 //保存文件
28 if (!file.exists()) {
29 //使用common.io工具包保存文件
30 FileUtils.copyFile(text[i], file);
31 }
32 }
33
34 return "success";
35 }
36
37}