詳解JavaWeb如何實現檔案上傳和下載功能
目錄
- 1. 檔案傳輸原理及介紹
- 2. Web檔案上傳
- 2.1我們用一個新的方式建立專案
- 2.2 導包
- 2.3 實用類介紹
- 2.4 pom.xml匯入需要的依賴
- 2.5 index.p
- 2.6 info.jsp
- 2.7 FileServlet
- 2.8 配置Servlet
- 2.9 測試結果
- 3. SpringMVC檔案上傳和下載
- 3.1 上傳
- 3.2 下載
1. 檔案傳輸原理及介紹
2. JavaWeb檔案上傳
2.1我們用一個新的方式建立專案
空專案會直接彈出框
把jdk版本設定好
點選確定後是比較乾淨的,啥都不會,不要慌,點選file->new->module。之後就和之前做過的一樣了
建立model:file,配置tomcat執行保證沒有錯誤
2.2 導包
可以選擇去maven倉庫中下,也可以在官網上搜出來然後複製到專案中,我們建立一個資料夾lib,然後如果從外面複製到專案中需要右鍵點選add as library新增到內庫中
上述只是講一個新建專案的方式,我後面還是按照之前的用maven進行了一個專案完成
2.3 實用類介紹
檔案上傳的注意事項
1.為保證伺服器安全,上傳檔案應該放在外界無法直接訪問的目錄下,比如放在WEB-INF目錄下。
2.為防止檔案覆蓋的現象發生,要為上傳檔案產生一個唯一的檔名,
- 加一個時間戳
- UUID
- md5
- 自己寫位運算演算法
3.要限制上傳檔案的最大值
4.可以限制上傳檔案的型別,在收到上傳檔名時,判斷後綴名是否合法。
需要用到的類詳解
ServletFileUpload負責處理上傳的檔案資料,並將表單中每個輸入項封賬成一個fileItem物件,在使用ServletFileUpload物件解析請求時需要DiskFileItemFactory物件。所以,我們需要在進行解析工作前構造好DiskFileItemFactory物件,通過ServletFileUpload物件的構造方法或setFileItemFactory()方法設定ServletFileUpload物件的fileItemFactory屬性。
FileItem類
在HTML頁面input必須有
<input type="file" name = "filename">
表單中如果包含一個檔案上傳輸入項的話,這個表單的enctype屬性就必須設定為multipart/form-data
常用方法介紹
//isFromField方法用於判斷FileItem類物件封裝的資料是一個普通文字表單還是一個檔案表單,如果是普通表單就返回true,否則返回false boolean isFormField(); //getFieldName方法用於返回表單標籤name屬性的值 String getFieldName(); //getString方法用於將FileItem物件中儲存的資料流內容以一個字串返回 String getString(); //getName方法用於獲得檔案上傳欄位中的檔名 String getName(); //以流的形式返回上傳檔案的資料內容 InputStream getInputStream(); //delete方法用來清空FileItem類物件中存放的主體內容。如果主題內容被儲存在臨時檔案中,delete方法將刪除該臨時檔案 void delete();
ServletFileUpload類
ServletFileUpload負責處理上傳的檔案資料,並將表單中每個輸入項封裝成一個FileItem物件中,使用其parseRequest(HttpServletRequest)方法可以將通過表單中每一個HTML標籤提交的資料封裝成一個FIleItem物件,然後以list列表的形式返回。使用該方法處理上傳檔案簡單易用
2.4 pom.xml匯入需要的依賴
<!--Servlet 依賴--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> </dependency> <!--JSP依賴--> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.3</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-io/commons-io --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency>
2.5 index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> <%--通過表單上傳檔案; get:上傳檔案大小有限制 post:上傳檔案大小沒有限制 ${pageContext.request.contextPath}獲取伺服器當前路徑 --%> <form action="${pageContext.request.contextPath}/upload.do" enctype="multipart/form-data" method="post"> 上傳使用者:<input type="text" name="username"><br/> <p><input type="file" name="file1"></p> <p><input type="file" name="file1"></p> <p><input type="submit"> | <input type="reset"></p> </form> </body> </html>
2.6 info.jsp
該頁面主要用於接受message
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <%=request.getAttribute("msg")%> </body> </html>
2.7 FileServlet
這裡的包一定要注意不要導錯了。另外這裡使用了封裝的方法讓結構看起來更簡潔
import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.ProgressListener; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.util.List; import java.util.UUID; public class FileServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req,HttpServletResponse resp) throws Servlethttp://www.cppcns.comException,IOException { doPost(req,resp); } @Override protected void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException { //判斷上傳的檔案是普通表單還是帶檔案的表單 if (!ServletFileUpload.isMultipartContent(req)) { return;//終止方法執行,說明這是一個普通的表單 } //建立上傳檔案的儲存路徑,建議在WEB-INF路徑下,安全,使用者無法直接訪問上傳的檔案 //獲得全域性的上下文,地址 String uploadPath = this.getServletContext().getRealPath("/WEB-INF/upload"); File uploadFile = new File(uploadPath); if (!uploadFile.exists()) { uploadFile.mkdir();//建立這個目錄 } //快取,臨時檔案 //臨時檔案,假如檔案超過了預期的大小,我們就把他放到一個臨時檔案中,過幾天激動刪除,或者提醒使用者轉存為永久 String tmpPath = this.getServletContext().getRealPath("/WEB-INF/tmp"); File tmpFile = new File(tmpPath); if (!tmpFile.exists()) { tmpFile.mkdir();//建立這個目錄 } //處理上傳的檔案,一般需要通過流來獲取,我們可以使用request.getInputStream(),原生態的檔案上傳流獲取, //上面的太麻煩,建議使用APache的檔案上傳元件來實現,common-fileupload,它需要依賴於commons-io元件 try { //1.建立DiskFileItemFactory物件,處理檔案上傳路徑或者大小限制的 DiskFileItemFactory factory = getDiskFileItemFactory(tmpFile); //2.獲取ServletFileUpload ServletFileUpload upload = getServletFileUpload(factory); //3.處理上傳檔案 String msg = uploadParseRequest(upload,req,uploadPath); //servlet請求轉發訊息 req.setAttribute("msg",msg); req.getRequestDispatcher("info.jsp").forward(req,resp); } catch (FileUploadException e) { e.printStackTrace(); } } public static DiskFileItemFactory getDiskFileItemFactory(File tmpFile) { DiskFileItemFactory factory = new DiskFileItemFactory(); //通過這個工廠設定一個緩衝區,當上傳的檔案大於這個緩衝區的時候,將他放到臨時檔案中 //可以設可以不設 factory.setSizeThreshold(1024 * 1024); factory.setRepository(tmpFile); return factory; } public static ServletFileUpload getServletFileUpload(DiskFileItemFactory factory) { //2.獲取ServletFileUpload ServletFileUpload upload = new ServletFileUpload(factory); //可以設,可以不設 //監聽檔案上傳進度 upload.setProgressListener(new ProgressListener() { //pContentLength:檔案大小 //pBytesRead:已經讀取到的檔案大小 @Override public void update(long pBytesRead,long pContentLength,int pItems) { System.out.println("總大小:" + pContentLength + "已上傳" + pBytesRead); } }); //處理亂碼問題 upload.setHeaderEncoding("UTF-8"); //設定單個檔案的最大值 upload.setFileSizeMax(1024 * 1024 * 10); //設定總共能夠上傳的檔案的大小 //1024 = 1kb * 1024 = 1M * 10 = 10M upload.setSizeMax(1024 * 1024 * 10); return upload; } public static String uploadParseRequest(ServletFileUpload upload,HttpServletRequest req,String uploadPath) throws FileUploadException,IOException { String msg = ""; //3.處理上傳檔案 //把前端請求解析,封裝成一個FileItem物件,需要從ServletFileUpload物件中獲取 List<FileItem> fileItems = upload.parseRequest(req); //每一個表單物件 for (FileItem fileItem : fileItems) { //判斷上傳的檔案是普通的表單還是帶檔案的表單 if (fileItem.isFormField()) { //getFieldName()指的是前端表單控制元件的name String name = fileItem.getFieldName(); String value = fileItem.getString("UTF-8");//處理亂碼 System.out.println(name + ":" + value); } else { //檔案的情況 //=====處理檔案 //拿到檔名字 String uploadFileName = fileItem.getName(); System.out.println("上傳的檔名:" + uploadFileName); if (uploadFileName.trim().equals("") || uploadFileName == null) { continue; } //獲得檔案上傳的檔名和字尾名;/images/boys/dajie.jpg 下面這塊不是必須的 String fileName = uploadFileName.substring(uploadFileName.lastIndexOf("/") + 1); String fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1); //如果檔案字尾名fileExtName不是我們所需要的就直接return,不處理,告訴使用者檔案型別不對 System.out.println("檔案資訊【件名:" + fileName + "---檔案型別" + fileExtName + "】"); //可以使用UUID(唯一識別的通用碼),保證檔名唯一 //UUID.randomUUID(),隨機生成一個唯一識別的通用碼 //網路傳輸中的東西,都需要序列化, //比如:POJO,實體類,如果想要在多個電腦上執行,需要進行傳輸===>需要把物件序列化 //implements Serializable :標記介面,JVM--> java棧 本地方法棧 ; native---》C++ String uuidPath = UUID.randomUUID().toString(); //===lhlQOKt處理檔案結束 //=====存放地址 //存到哪?uploadPath //檔案真實存在的路徑realPath String realPath = uploadPath + "/" + uuidPath; //給每個檔案建立一個對應的資料夾 File realPathFile = new File(realPath); if (!realPathFile.exists()) { realPathFile.mkdir(); } //=====存放地址完畢 //=====檔案傳輸 //獲得檔案上傳的流 InputStream inputStream = fileItem.getInputStream(); //建立一個檔案輸出流 //realPath = 真實的資料夾 //差了一個檔案,加上輸出的檔案的名字+"/" +uuidFileName FileOutputStream fos = new FileOutputStream(realPath + "/" + fileName); //建立一個緩衝區 byte[] buffer = new byte[1024 * 1024]; //判斷是否讀取完畢 int len = 0; //如果大於0說明還存在資料 while ((len = inputStream.read(buffer)) > 0) { fos.write(buffer,len); } //關閉流 fos.close(); inputStream.close(); msg = "檔案上傳成功!"; fileItem.delete();//上傳成功,清楚臨時檔案 } } return msg; } }
2.8 配置Servlet
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <servlet> <servlet-name>FileServlet</servlet-name> <servlet-class>com.hxl.servlet.FileServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>FileServlet</servlet-name> <url-pattern>/upload.do</url-pattern> </servlet-mapping> </web-app>
2.9 測試結果
3. SpringMVC檔案上傳和下載
3.1 上傳
在controller中有兩種方式
新建一個module,一套流程整體下來。測試能執行即可
−−>匯入jar包
<!--檔案上傳--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> </dependency>
−−>index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>檔案上傳和下載</title> </head> <body> <form action="${pageContext.request.contextPath}/upload" enctype="multipart/form-data" method="post"> <input type="file" name="file"/> <input type="submit" value="upload"> </form> </body> </html>
−−>applicationContext.xml中配置bean
<!--檔案上傳配置--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 請求的編碼格式,必須和jSP的pageEncoding屬性一致,以便正確讀取表單的內容,預設為ISO-8859-1 --> <property name="defaultEncoding" value="utf-8"/> <!-- 上傳檔案大小上限,單位為位元組(10485760=10M) --> <property name="maxUploadSize" value="10485760"/> <property name="maxInMemorySize" value="40960"/> </bean>
−−>FileController
package com.hxl.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
@RestController
public class FileController {
//@RequestParam("file") 將name=file控制元件得到的檔案封裝成CommonsMultipartFile 物件
//批量上傳CommonsMultipartFile則為陣列即可
@RequestMapping("/upload")
public String fileUpload(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request) throws IOException {
//獲取檔名 : file.getOriginalFilename();
String uploadFileName = file.getOriginalFilename();
//如果檔名為空,直接回到首頁!
if ("".equals(uploadFileName)){
return "redirect:/index.jsp";
}
www.cppcns.com System.out.println("上傳檔名 : "+uploadFileName);
//上傳路徑儲存設定
String path = request.getServletContext().getRealPath("/upload");
//如果路徑不存在,建立一個
File realPath = new File(path);
if (!realPath.exists()){
realPath.mkdir();
}
System.out.println("上傳檔案儲存地址:"+realPath);
InputStream is = file.getInputStream(); //檔案輸入流
OutputStream os = new FileOutputStream(new File(realPath,uploadFileName)); //檔案輸出流
//讀取寫出
int len=0;
byte[] buffer = new byte[1024];
while ((len=is.read(buffer))!=-1){
os.write(buffer,len);
os.flush();
}
os.close();
is.close();
return "redirect:/index.jsp";
}
/*
* 採用file.Transto 來儲存上傳的檔案
*/
@RequestMapping("/upload2")
public String fileUpload2(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request) throws IOException {
//上傳路徑儲存設定
String path = request.getServletContext().getRealPath("/upload");
File realPath = new File(path);
if (!realPath.exists()){
realPath.mkdir();
}
//上傳檔案地址
System.out.println("上傳檔案儲存地址:"+realPath);
//通過CommonsMultipartFile的方法直接寫檔案(注意這個時候)
file.transferTo(new File(realPath +"/"+ file.getOriginalFilename()));
return "redirect:/index.jsp";
}
}
−−>測試:
3.2 下載
1、設定 response 響應頭
2、讀取檔案 – InputStream
3、寫出檔案 – OutputStream
4、執行操作
5、關閉流 (先開後關)
−−>index.jsp
<a href="${pageContext.request.contextPath}/download" rel="external nofollow" >點選下載</a>
−−>增加一個upload檔案
並且把要下載的圖片弄進去
−−>controller
@RequestMapping(value="/download") public String downloads(HttpServletResponse response,HttpServletRequest request) throws Exception{ //要下載的圖片地址 String path = request.getServletContext().getRealPath("/upload"); //String fileName = "你想要下載的檔案,要加上字尾"; String fileName = "1.jpg"; //1、設定response 響應頭 response.reset(); //設定頁面不快取,清空buffer response.setCharacterEncoding("UTF-8"); //字元編碼 response.setContentType("multipart/form-data"); //二進位制傳輸資料 //設定響應頭 response.setHeader("Content-Disposition","attachment;fileName="+ URLEncoder.encode(fileName,"UTF-8")); File file = new File(path,fileName); //2、 讀取檔案--輸入流 InputStream input=new FileInputStream(file); //3、 寫出檔案--輸出流 OutputStream out = response.getOutputStream(); byte[] buff =new byte[1024]; int index=0; //4、執行 寫出操作 while((index= input.read(buff))!= -1){ out.write(buff,index); out.flush(); } out.close(); input.close(); return "ok"; }
−−>測試:
以上就是詳解JavaWeb如何實現檔案上傳和下載功能的詳細內容,更多關於JavaWeb檔案上傳和下載的資料請關注我們其它相關文章!