java 檔案上傳

來源:互聯網
上載者:User

1. 頁面內容

<c:url value="/uploadPic" var="weiboPublictUrl" />
<form method="POST" action="${weiboPublictUrl}" ENCTYPE="multipart/form-data">
    <p>Upload Picture
    <p>
        <input type="file"  name="uploadPath" id="uploadPath" size="62"  maxlength="3"/>
        <input type="submit" value="UploadPicture" />    
</form>

2.java代碼

private String uploadPic(HttpServletRequest request,
            HttpServletResponse response) throws IOException, ServletException {
        PrintWriter writer = response.getWriter();
        final long MAX_SIZE = 3 * 1024 * 1024;// 設定上傳檔案最大為 3M
        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        DiskFileItemFactory dfif = new DiskFileItemFactory();
        dfif.setSizeThreshold(4096);// 設定上傳檔案時用於臨時存放檔案的記憶體大小,這裡是4K.多於的部分將臨時存在硬碟
        File file_dir = new File("d:\\filetemp");
        if (!file_dir.exists()) {
            file_dir.mkdir();
        }
        dfif.setRepository(file_dir);// 設定存放臨時檔案的目錄,web根目錄下的ImagesUploadTemp目錄
        // 用以上工廠執行個體化上傳組件
        ServletFileUpload sfu = new ServletFileUpload(dfif);
        // 設定最大上傳尺寸
        sfu.setSizeMax(MAX_SIZE);
        // 從request得到 所有 上傳域的列表
        List fileList = null;
        try {
            fileList = sfu.parseRequest(request);
        } catch (FileUploadException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // 沒有檔案上傳
        if (fileList == null || fileList.size() == 0) {
            writer.write("{\"picUrl:\":\"沒有檔案上傳\"}");
        }
        // 得到所有上傳的檔案
        Iterator fileItr = fileList.iterator();
        // 迴圈處理所有檔案
        while (fileItr.hasNext()) {
            FileItem fileItem = null;
            String fpath = "";
            long size = 0;
            // 得到當前檔案
            fileItem = (FileItem) fileItr.next();
            if (fileItem.isFormField()) {
                // 如果不是上傳域,而是普通的表單域(如:<input type="text|radio">)則在此進行處理
            }
            // 忽略簡單form欄位而不是上傳域的檔案域(<input type="text" />等)
            if (fileItem == null || fileItem.isFormField()) {
                continue;
            }
            // 得到檔案的完整路徑     
            fpath = fileItem.getName();
            // 得到檔案的大小     
            size = fileItem.getSize();
            if ("".equals(fpath) || size == 0) {
                writer.write("{\"picUrl\":\"請選擇上傳檔案\"}");
            }
            // 得到去除路徑的檔案名稱     
            String t_name = fpath.substring(fpath.lastIndexOf("\\") + 1);
            // 得到檔案的副檔名(無副檔名時將得到全名)     
            String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1);
            // 根據系統時間產生上傳後儲存的檔案名稱     
            // String prefix = String.valueOf(now);
            // 儲存的最終檔案完整路徑,儲存在web根目錄下的目錄下     
            String mms = String.valueOf(System.currentTimeMillis());
            String u_name = request.getRealPath("/") + "resources/uploaded/"
                    + mms + "_" + t_name + "." + t_ext;
            File file = new File(u_name);
            try {
                fileItem.write(file);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
                     
            return "redirect:/weibo/public";
            //request.getRequestDispatcher("/weibo/public?picUrl=" + u_name).forward(request, response);
            //writer.write("{\"picUrl\":\"" + u_name + "\"}");
            
        }
        return "redirect:/weibo/public";
    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.