現代軟體工程第六次作業

來源:互聯網
上載者:User

標籤:

項目中關於實現檔案上傳功能的總結:

1. 環境搭建

  建立web工程過程省略,僅需在工程中添加如下兩個jar包:

  commons-fileupload-1.2.1.jar

  commons-io-2.0.jar     資源可在網上下載

2. 前段準備 

<form action="uploadServlet" method="post" enctype="multipart/form-data">    FileName:<input type="text" name="filename" accept="image/gif,image/jpeg,image/png">    File:<input type="file" name="file"/>    <input type="submit" value="Submit"/></form>

 

注意:I.   表單提交方式為post
   II. 使用 file 的表單域: <input type="file" name="file" accept="image/gif,image/jpeg,image/png"/> accept可以限制上傳檔案類型
   III. 使用 multipart/form-data 的請求編碼方式;資料將以二進位形式傳輸

3. 伺服器端準備

  建立UploadServletU用於提供服務

  關鍵代碼如下: 

  注意:由於表單是以二進位形式進行傳輸,在服務端可能會出現亂碼。本人親測:使用String fieldValue = item.getString("utf-8");可有效解決

      文本域中文亂碼問題。

//1. 得到FileItem的集合DiskFileItemFactory factory = new DiskFileItemFactory();//設定記憶體中最多可以存放的上傳檔案的大小, 若超出則把檔案寫到一個臨時檔案夾中. 以 byte 為單位factory.setSizeThreshold(1024 * 500);//設定那個臨時檔案夾File tempDirectory = new File("/resources/tempDirectory");factory.setRepository(tempDirectory);ServletFileUpload upload = new ServletFileUpload(factory);upload.setHeaderEncoding("utf-8");//設定上傳檔案的總的大小. 也可以設定單個檔案的大小.upload.setSizeMax(1024 * 1024 * 5);    InputStream in = null;OutputStream out = null;// 解析requesttry {List<FileItem> /* FileItem */ items = upload.parseRequest(request);//2. 遍曆FileItem集合 若是表單域 則列印資訊 否則儲存在磁碟上for (FileItem item : items) {  if (item.isFormField()) {    String fieldName = item.getFieldName();    String fieldValue = item.getString("utf-8");    System.out.println(fieldName+": " +fieldValue);  } else {    String fieldName = item.getFieldName();    String fileName = item.getName();    String contentType = item.getContentType();    long sizeInBytes = item.getSize();    //判斷表單網域名稱是否為img    if (fieldName.equals("img")) {      //判斷是否為圖片類型      if (contentType.equals("image/png") ||        contentType.equals("image/jpeg") ||        contentType.equals("image/gif")) {        //判斷圖片是否超過5M        if (sizeInBytes <= 5 * 1024 * 1024) {          in = item.getInputStream();          byte[] buffer = new byte[1024];          int len = 0;          fileName = System.currentTimeMillis() + fileName;          img = fileName;          fileName = this.getServletContext().getRealPath("/") + "resources\\imgs\\" + fileName;          System.out.println(fileName);          out = new FileOutputStream(fileName);          while ((len = in.read(buffer)) != -1) {            out.write(buffer, 0, len);          }        }      }    }  }}} catch (FileUploadException e) {  e.printStackTrace();} finally {  if (out != null) {    out.close();  }   if (in != null) {    in.close();  }}

 

    

現代軟體工程第六次作業

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.