一直猶豫什麼時候寫第一篇部落格,總覺得第一篇就應該留下一個好印象。現在看看,還不如早點寫,養成一個好習慣。
這篇文章是關于java中檔案上傳的功能的實作。其實說到檔案上傳,我的第一反應就是将檔案放進request中,然後servlet對檔案的一系列操作!
是以這裡面有兩個問題:
1、将檔案放進request中,這個并不難。 在将表單的頭中加enctype=”multipart/form-data”。代碼如下:
<!--enctype="multipart/form-data"将上傳格式轉化為二進制形式 -->
<form action = "upload" method = "post" enctype="multipart/form-data" >
<input type = "file" name = "uploadfile"/><br/>
<input type = "submit" value = "确定!"/>
</form>
至于第二個問題,就是servlet中關于檔案的處理情況。也就是對request
中的檔案進行提取。這裡就要用到commons-fileupload 和commons-io兩個jar包了。主要執行過程分為如下幾步:
以表單集合的形式展示出來。
2、對每一個表單檔案進行解析,将表單中的檔案提取出來。轉化為檔案流的形式。
3、将檔案流寫入到項目中(不建議使用,一般對于大型檔案都是會存在本地,或是伺服器本地,将路徑存于資料庫)。本人在寫入的時候,由于配置的原因,使用this.getServletContext().getRealPath(“/WEB-INF/upload”)獲得的并不是項目中的位址,而是eclipse中預設的server的相關位置。讀者使用時,應該注意。Servlet代碼如下:
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
// 擷取輸入流
InputStream is = request.getInputStream();
try {
// 獲得檔案處理工廠
DiskFileItemFactory factory = new DiskFileItemFactory();
// 擷取解析器
ServletFileUpload upload = new ServletFileUpload(factory);
// 設定編碼
upload.setHeaderEncoding("utf-8");
// 判斷送出上來的資料是否是表單資料
if (!ServletFileUpload.isMultipartContent(request)) {
return;
}
// 使用ServletFileUpload解析器解析上傳資料,解析結果傳回的是一個List<FileItem>集合,
// 每一個FileItem對應一個Form表單的輸入項
List<FileItem> list = upload.parseRequest(request);
for (FileItem item : list) {
// 如果fileitem中封裝的是普通輸入項的資料
if (item.isFormField()) {
String name = item.getFieldName();
String value = item.getString("UTF-8");
System.out.println(name + "=" + value);
} else {// 如果fileitem中封裝的是上傳檔案, 得到上傳的檔案名稱
String filename = item.getName();
System.out.println(filename);
if (filename == null || filename.trim().equals("")) {
continue;
}
// 擷取檔案 名
filename = filename
.substring(filename.lastIndexOf("\\") + );
InputStream in = item.getInputStream();
// 檔案輸出路徑
FileOutputStream out = new FileOutputStream("D:/workspace/upload/WebContent/WEB-INF/upload/"+
filename);
byte buffer[] = new byte[];
int len = ;
// 循環寫入資料
while ((len = in.read(buffer)) > ) {
out.write(buffer, , len);
out.flush();
}
in.close();
out.close();
// 删除處理檔案上傳時生成的臨時檔案
item.delete();
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
//成功之後跳轉到成功界面
request.getRequestDispatcher("/success.jsp").forward(request, response);
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
檔案上傳代碼如上,若有不足還望各位提醒。如有疑問,歡迎一起探讨。