java中,文件上傳功能

一直猶豫什麼時候寫第一篇博客,總覺得第一篇就應該留下一個好印象。現在看看,還不如早點寫,養成一個好習慣。
這篇文章是關於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("\\") + 1);
                    InputStream in = item.getInputStream();
                    // 文件輸出路徑
                    FileOutputStream out = new FileOutputStream("D:/workspace/upload/WebContent/WEB-INF/upload/"+
                             filename);
                    byte buffer[] = new byte[1024];
                    int len = 0;
                    // 循環寫入數據
                    while ((len = in.read(buffer)) > 0) {
                        out.write(buffer, 0, 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);
    }

文件上傳代碼如上,若有不足還望各位提醒。如有疑問,歡迎一起探討。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章