Servlet上傳文件詳細(xì)解析以及注意事項(xiàng)
準(zhǔn)備階段,下載需要的包:
在Servlet中進(jìn)行文件上傳需要用到外部的類庫(kù),apache提供了這些類庫(kù), 主要需要commons-fileupload.jar和commons-io.jar
下載的步驟如下:
進(jìn)入www.apache.org網(wǎng)站, ——>在Projects下找到commons,點(diǎn)擊進(jìn)入——>找到Components下的FileUpload,點(diǎn)擊進(jìn)入就可以找到下載
頁(yè)面如下:
可以看到這里有開發(fā)指南和下載地址,如果要詳細(xì)學(xué)習(xí),慢慢看這里的資源就可以了。
commons-io.jar包的下載地址:http://commons.apache.org/fileupload/dependencies.html
把兩個(gè)jar包放到WEB-INF的lib目錄下。
開發(fā)階段:
上傳頁(yè)面:index.jsp
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
- <title>文件上傳</title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
- <!--
- <link rel="stylesheet" type="text/css" href="styles.css">
- -->
- </head>
- <body>
- <form action="upload" method="post" enctype="multipart/form-data">
- 文件別名:<input type="text" name="filename"><br>
- 選擇文件:<input type="file" name="fileupload"><br>
- <input type="submit" value="提交">
- </form>
- </body>
- </html>
這里注意第24行,上傳文件時(shí)要指定提交方法method="post", 信息類型為enctype="multipart/form-data"
上傳功能servlet:FileUpload
- package com.sunflower.servlet;
- import java.io.File;
- import java.io.IOException;
- import java.util.Iterator;
- import java.util.List;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.apache.commons.fileupload.FileItem;
- import org.apache.commons.fileupload.FileItemFactory;
- import org.apache.commons.fileupload.FileUploadException;
- import org.apache.commons.fileupload.disk.DiskFileItemFactory;
- import org.apache.commons.fileupload.servlet.ServletFileUpload;
- public class FileUpload extends HttpServlet {
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- req.setCharacterEncoding("UTF-8");
- fileControl(req, resp);
- }
- /**
- * 上傳文件的處理
- */
- private void fileControl(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
- // 在解析請(qǐng)求之前先判斷請(qǐng)求類型是否為文件上傳類型
- boolean isMultipart = ServletFileUpload.isMultipartContent(req);
- // 文件上傳處理工廠
- FileItemFactory factory = new DiskFileItemFactory();
- // 創(chuàng)建文件上傳處理器
- ServletFileUpload upload = new ServletFileUpload(factory);
- // 開始解析請(qǐng)求信息
- List items = null;
- try {
- items = upload.parseRequest(req);
- }
- catch (FileUploadException e) {
- e.printStackTrace();
- }
- // 對(duì)所有請(qǐng)求信息進(jìn)行判斷
- Iterator iter = items.iterator();
- while (iter.hasNext()) {
- FileItem item = (FileItem) iter.next();
- // 信息為普通的格式
- if (item.isFormField()) {
- String fieldName = item.getFieldName();
- String value = item.getString();
- req.setAttribute(fieldName, value);
- }
- // 信息為文件格式
- else {
- String fileName = item.getName();
- int index = fileName.lastIndexOf("\\");
- fileName = fileName.substring(index + 1);
- req.setAttribute("realFileName", fileName);
- // 將文件寫入
- // String path = req.getContextPath();
- // String directory = "uploadFile";
- // String basePath = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + path + "/" + directory;
- String basePath = req.getRealPath("/uploadFile");
- File file = new File(basePath, fileName);
- try {
- item.write(file);
- }
- catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- try {
- req.getRequestDispatcher("/uploadsuccess.jsp").forward(req, resp);
- }
- catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
這里要注意第66~68行,將文件上傳到Web項(xiàng)目的"uploadFile"文件夾中,如果用這種方法得到的路徑是"http://localhost:8080/upload/uploadFile", 而創(chuàng)建File類用的路徑是絕對(duì)路徑,這樣就會(huì)出問題,所以這里要用的是得到真實(shí)路徑的方法HttpServletRequest.getRealPath().
以上是最簡(jiǎn)單的文件上傳,如果要加入上傳的限制可以在DiskFileItemFactory和ServletFileUpload中進(jìn)行限制:
在34行后加入:
- //創(chuàng)建臨時(shí)文件目錄
- File tempFile = new File(req.getRealPath("/temp"));
- //設(shè)置緩存大小
- ((DiskFileItemFactory) factory).setSizeThreshold(1024*1024);
- //設(shè)置臨時(shí)文件存放地點(diǎn)
- ((DiskFileItemFactory) factory).setRepository(tempFile);
注意第72行的FileItem.write()方法,如果使用了這個(gè)方法寫入文件,那么臨時(shí)文件會(huì)被系統(tǒng)自動(dòng)刪除.
在38行后加入:
- //將頁(yè)面請(qǐng)求傳遞信息最大值設(shè)置為50M
- upload.setSizeMax(1024*1024*50);
- //將單個(gè)上傳文件信息最大值設(shè)置為6M
- upload.setFileSizeMax(1024*1024*6);
原文鏈接:http://www.cnblogs.com/hanyuan/archive/2012/06/09/upload.html