JavaWeb中的檔案上傳
阿新 • • 發佈:2018-12-19
1.匯入相應的jar包
在這裡我是用Maven匯入相應的jar包。當然也可以在網上尋找commons-io-2.0.1.jar和commons-fileupload-1.2.2.jar包。
<dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.0.1</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.2.2</version> </dependency>
2.實現檔案上傳
寫一個jsp檔案
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>檔案上傳</title> </head> <body> <div> <!-- 注意!表單的enctype屬性一定要由原來的文字編碼格式改成下面的二進位制文字編碼格式 在使用包含上傳空間的表單時,必須使用該值 (multipart/form-data) --> <form action="${pageContext.request.contextPath}/user.action?method=uploadFile" method="post" enctype="multipart/form-data"> <h1>最基本的檔案上傳方式</h1> <hr> <fieldset> <legend>檔案上傳</legend> 使用者名稱:<input type="text" name="username"> <br> <input type="file" name="file"> <br> <input type="submit" value="提交"> </fieldset> </form> </div> </body> </html>
然後寫一個後臺的實現程式碼
/** * 上傳檔案 * @param request * @param response */ public void uploadFile(HttpServletRequest request,HttpServletResponse response) { //判斷編碼方式是否為 multipart/form-data boolean isMutipart = ServletFileUpload.isMultipartContent(request); if(isMutipart) { InputStream is = null; FileOutputStream fos = null; //用於處理檔案上傳 ServletFileUpload upload = new ServletFileUpload(); //解決上傳檔名的中文亂碼 upload.setHeaderEncoding("UTF-8"); try { //從request中按順序解析出資料 FileItemIterator iterator = upload.getItemIterator(request); while(iterator.hasNext()) { FileItemStream fis = iterator.next(); //建立一個輸入流來獲取fis中的資料, //使用了Multipart之後就表示通過位元組資料進行傳輸,所以需要將其轉化為輸入流進行處理 is = fis.openStream(); if(fis.isFormField()) {//判斷是否為表單域 //是表單域就輸出表單域的名稱 System.out.println("屬性名:"+fis.getFieldName()); //將流中的資料轉化成String System.out.println("資料:"+Streams.asString(is)); }else {//如果不是表單域,就說明是上傳的檔案 System.out.println("屬性名:"+fis.getFieldName()); System.out.println("上傳檔案的路徑名:"+fis.getName()); //獲取真實路徑 //String path = request.getSession().getServletContext().getRealPath("/fileSave"); //上傳檔案所儲存的位置 String path = "E:\\log"; //獲取檔名 String fileName = fis.getName().substring(fis.getName().lastIndexOf("\\")+1); System.out.println(fileName); path = path+"\\"+fileName; System.out.println(path); //將上傳的檔案寫入到另外一個路徑中 fos = new FileOutputStream(path); byte [] buf = new byte[1024]; int length = 0; while((length=is.read(buf))>0) { fos.write(buf,0,length); } System.out.println(); } } } catch (FileUploadException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { if(is!=null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if(fos!=null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
參考:
https://blog.csdn.net/sinat_28050007/article/details/53290321