Servlet中文件上傳的幾種方式


  上傳文件,因為上傳的都是二進制數據,所以在Servlet中就不能直接用request.getParameter();方法進行數據的獲取,需要借助第三方jar包對上傳的二進制文件進行解析。常用的方式如下:

一:使用SmartUpload.jar

  它是一個商業類庫,解析request過程中,數據是存放在內存中的,因此速度比較快,但是上傳大文件的時候會出現內存溢出。

二:commons-fileupload.jar (Apache commons)、commons-io.jar

UploadFileServlet .java
public class UploadFileServlet extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().println("請以POST方式訪問該URL");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //設置請求和響應的編碼格式
        String encoding = getServletContext().getInitParameter("encoding");
        req.setCharacterEncoding(encoding);
        resp.setCharacterEncoding(encoding);
        resp.setContentType("text/html");
        
        //核心Api
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload fileUpload = new ServletFileUpload(factory);
        
        //判斷是否是muitipart/form-data類型
        if(!ServletFileUpload.isMultipartContent(req)) {
            resp.getWriter().println("表單的enctype屬性不是multipart/form-data類型");
        }
        
        //設置單個文件上傳大小 2M
        fileUpload.setFileSizeMax(2*1024*1024); 
        //設置總上傳文件大小(有時候一次性上傳多個文件,需要有一個上限,此處為10M)
        fileUpload.setSizeMax(10*1024*1024);
        //設置上傳監聽器[參數為自定義的監聽器]
        fileUpload.setProgressListener(new ListenerUploadProgress());
        //解析請求
        try {
            List<FileItem> parseRequest = fileUpload.parseRequest(req);
            //獲取數據
            for (FileItem fileItem : parseRequest) {
                //判斷數據類型是不是普通的form表單字段
                if(!fileItem.isFormField()) {
                    //上傳文件
                    String fileName = fileItem.getName();
                    InputStream fileStream = fileItem.getInputStream();
                    //定義保存的父路徑
                    String parentDir = this.getServletContext().getRealPath("/WEB-INF/upload");
                    //使用UUID+文件名的方式,避免文件重名
                    String realFileName = UUID.randomUUID().toString()+"-"+fileName;
                    //創建要保存的文件
                    File file = new File(parentDir,realFileName);
                    //判斷文件夾是否存在
                    if(!file.getParentFile().exists()) {
                        //創建文件夾[多級文件夾]file.madir是創建單一文件夾
                        file.getParentFile().mkdirs();
                    }
                    
                    //創建輸出流
                    OutputStream out = new FileOutputStream(file);
                    //創建字節緩存
                    byte[] buffer = new byte[1024];
                    int len = -1;
                    //一次讀取1kb(1024byte),返回-1表明讀取完畢
                    while((len = fileStream.read(buffer))!=-1) {
                        //一次寫入1kb(1024byte)
                        out.write(buffer,0, len);
                    }
                    
                    //沖刷流資源
                    out.flush();
                    //關閉流
                    out.close();
                    fileStream.close();
                    
                }else {
                    //普通字段
                    
                    //字段名
                    String fieldName = fileItem.getFieldName();
                    //字段值
                    String fieldValue = fileItem.getString();
                    System.out.println(fieldName+":"+fieldValue);
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }        
    }
}
ListenerUploadProgress.java
public class ListenerUploadProgress implements ProgressListener {
    
    /**
     * @param bytesRead 已經讀取的字節數
     * @param contentLength 文件總長度
     * @param items 當前上傳的是哪個文件
     */
    @Override
    public void update(long bytesRead, long contentLength, int items) {
        System.out.println(bytesRead);
        System.out.println(contentLength);
        System.out.println(items);
    }
    
    //*前端可以根據該信息寫一個上傳進度條
}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM