詳解JavaWeb如何實(shí)現(xiàn)文件上傳和下載功能
1. 文件傳輸原理及介紹
2. JavaWeb文件上傳
2.1我們用一個(gè)新的方式創(chuàng)建項(xiàng)目
空項(xiàng)目會(huì)直接彈出框
把jdk版本設(shè)置好
點(diǎn)擊確定后是比較干凈的,啥都不會(huì),不要慌,點(diǎn)擊file->new->module。之后就和之前做過(guò)的一樣了
創(chuàng)建model:file,配置tomcat運(yùn)行保證沒(méi)有錯(cuò)誤
2.2 導(dǎo)包
可以選擇去maven倉(cāng)庫(kù)中下,也可以在官網(wǎng)上搜出來(lái)然后復(fù)制到項(xiàng)目中,我們創(chuàng)建一個(gè)文件夾lib,然后如果從外面復(fù)制到項(xiàng)目中需要右鍵點(diǎn)擊add as library添加到內(nèi)庫(kù)中
上述只是講一個(gè)新建項(xiàng)目的方式,我后面還是按照之前的用maven進(jìn)行了一個(gè)項(xiàng)目完成
2.3 實(shí)用類(lèi)介紹
文件上傳的注意事項(xiàng)
1.為保證服務(wù)器安全,上傳文件應(yīng)該放在外界無(wú)法直接訪(fǎng)問(wèn)的目錄下,比如放在WEB-INF目錄下。
2.為防止文件覆蓋的現(xiàn)象發(fā)生,要為上傳文件產(chǎn)生一個(gè)唯一的文件名,
- 加一個(gè)時(shí)間戳
- UUID
- md5
- 自己寫(xiě)位運(yùn)算算法
3.要限制上傳文件的最大值
4.可以限制上傳文件的類(lèi)型,在收到上傳文件名時(shí),判斷后綴名是否合法。
需要用到的類(lèi)詳解
ServletFileUpload負(fù)責(zé)處理上傳的文件數(shù)據(jù),并將表單中每個(gè)輸入項(xiàng)封賬成一個(gè)fileItem對(duì)象,在使用ServletFileUpload對(duì)象解析請(qǐng)求時(shí)需要DiskFileItemFactory對(duì)象。所以,我們需要在進(jìn)行解析工作前構(gòu)造好DiskFileItemFactory對(duì)象,通過(guò)ServletFileUpload對(duì)象的構(gòu)造方法或setFileItemFactory()方法設(shè)置ServletFileUpload對(duì)象的fileItemFactory屬性。
FileItem類(lèi)
在HTML頁(yè)面input必須有
<input type="file" name = "filename">
表單中如果包含一個(gè)文件上傳輸入項(xiàng)的話(huà),這個(gè)表單的enctype屬性就必須設(shè)置為multipart/form-data
常用方法介紹
//isFromField方法用于判斷FileItem類(lèi)對(duì)象封裝的數(shù)據(jù)是一個(gè)普通文本表單還是一個(gè)文件表單,如果是普通表單就返回true,否則返回false boolean isFormField(); //getFieldName方法用于返回表單標(biāo)簽name屬性的值 String getFieldName(); //getString方法用于將FileItem對(duì)象中保存的數(shù)據(jù)流內(nèi)容以一個(gè)字符串返回 String getString(); //getName方法用于獲得文件上傳字段中的文件名 String getName(); //以流的形式返回上傳文件的數(shù)據(jù)內(nèi)容 InputStream getInputStream(); //delete方法用來(lái)清空FileItem類(lèi)對(duì)象中存放的主體內(nèi)容。如果主題內(nèi)容被保存在臨時(shí)文件中,delete方法將刪除該臨時(shí)文件 void delete();
ServletFileUpload類(lèi)
ServletFileUpload負(fù)責(zé)處理上傳的文件數(shù)據(jù),并將表單中每個(gè)輸入項(xiàng)封裝成一個(gè)FileItem對(duì)象中,使用其parseRequest(HttpServletRequest)方法可以將通過(guò)表單中每一個(gè)HTML標(biāo)簽提交的數(shù)據(jù)封裝成一個(gè)FIleItem對(duì)象,然后以list列表的形式返回。使用該方法處理上傳文件簡(jiǎn)單易用
2.4 pom.xml導(dǎo)入需要的依賴(lài)
<!--Servlet 依賴(lài)--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> </dependency> <!--JSP依賴(lài)--> <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> <%--通過(guò)表單上傳文件; get:上傳文件大小有限制 post:上傳文件大小沒(méi)有限制 ${pageContext.request.contextPath}獲取服務(wù)器當(dāng)前路徑 --%> <form action="${pageContext.request.contextPath}/upload.do" enctype="multipart/form-data" method="post"> 上傳用戶(hù):<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
該頁(yè)面主要用于接受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
這里的包一定要注意不要導(dǎo)錯(cuò)了。另外這里使用了封裝的方法讓結(jié)構(gòu)看起來(lái)更簡(jiǎn)潔
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 ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //判斷上傳的文件是普通表單還是帶文件的表單 if (!ServletFileUpload.isMultipartContent(req)) { return;//終止方法運(yùn)行,說(shuō)明這是一個(gè)普通的表單 } //創(chuàng)建上傳文件的保存路徑,建議在WEB-INF路徑下,安全,用戶(hù)無(wú)法直接訪(fǎng)問(wèn)上傳的文件 //獲得全局的上下文,地址 String uploadPath = this.getServletContext().getRealPath("/WEB-INF/upload"); File uploadFile = new File(uploadPath); if (!uploadFile.exists()) { uploadFile.mkdir();//創(chuàng)建這個(gè)目錄 } //緩存,臨時(shí)文件 //臨時(shí)文件,假如文件超過(guò)了預(yù)期的大小,我們就把他放到一個(gè)臨時(shí)文件中,過(guò)幾天激動(dòng)刪除,或者提醒用戶(hù)轉(zhuǎn)存為永久 String tmpPath = this.getServletContext().getRealPath("/WEB-INF/tmp"); File tmpFile = new File(tmpPath); if (!tmpFile.exists()) { tmpFile.mkdir();//創(chuàng)建這個(gè)目錄 } //處理上傳的文件,一般需要通過(guò)流來(lái)獲取,我們可以使用request.getInputStream(),原生態(tài)的文件上傳流獲取, //上面的太麻煩,建議使用APache的文件上傳組件來(lái)實(shí)現(xiàn),common-fileupload,它需要依賴(lài)于commons-io組件 try { //1.創(chuàng)建DiskFileItemFactory對(duì)象,處理文件上傳路徑或者大小限制的 DiskFileItemFactory factory = getDiskFileItemFactory(tmpFile); //2.獲取ServletFileUpload ServletFileUpload upload = getServletFileUpload(factory); //3.處理上傳文件 String msg = uploadParseRequest(upload, req, uploadPath); //servlet請(qǐng)求轉(zhuǎn)發(fā)消息 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(); //通過(guò)這個(gè)工廠設(shè)置一個(gè)緩沖區(qū),當(dāng)上傳的文件大于這個(gè)緩沖區(qū)的時(shí)候,將他放到臨時(shí)文件中 //可以設(shè)可以不設(shè) factory.setSizeThreshold(1024 * 1024); factory.setRepository(tmpFile); return factory; } public static ServletFileUpload getServletFileUpload(DiskFileItemFactory factory) { //2.獲取ServletFileUpload ServletFileUpload upload = new ServletFileUpload(factory); //可以設(shè),可以不設(shè) //監(jiān)聽(tīng)文件上傳進(jìn)度 upload.setProgressListener(new ProgressListener() { //pContentLength:文件大小 //pBytesRead:已經(jīng)讀取到的文件大小 @Override public void update(long pBytesRead, long pContentLength, int pItems) { System.out.println("總大小:" + pContentLength + "已上傳" + pBytesRead); } }); //處理亂碼問(wèn)題 upload.setHeaderEncoding("UTF-8"); //設(shè)置單個(gè)文件的最大值 upload.setFileSizeMax(1024 * 1024 * 10); //設(shè)置總共能夠上傳的文件的大小 //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.處理上傳文件 //把前端請(qǐng)求解析,封裝成一個(gè)FileItem對(duì)象,需要從ServletFileUpload對(duì)象中獲取 List<FileItem> fileItems = upload.parseRequest(req); //每一個(gè)表單對(duì)象 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,不處理,告訴用戶(hù)文件類(lèi)型不對(duì) System.out.println("文件信息【件名:" + fileName + "---文件類(lèi)型" + fileExtName + "】"); //可以使用UUID(唯一識(shí)別的通用碼),保證文件名唯一 //UUID.randomUUID(),隨機(jī)生成一個(gè)唯一識(shí)別的通用碼 //網(wǎng)絡(luò)傳輸中的東西,都需要序列化, //比如:POJO,實(shí)體類(lèi),如果想要在多個(gè)電腦上運(yùn)行,需要進(jìn)行傳輸===>需要把對(duì)象序列化 //implements Serializable :標(biāo)記接口,JVM--> java棧 本地方法棧 ; native---》C++ String uuidPath = UUID.randomUUID().toString(); //===處理文件結(jié)束 //=====存放地址 //存到哪?uploadPath //文件真實(shí)存在的路徑realPath String realPath = uploadPath + "/" + uuidPath; //給每個(gè)文件創(chuàng)建一個(gè)對(duì)應(yīng)的文件夾 File realPathFile = new File(realPath); if (!realPathFile.exists()) { realPathFile.mkdir(); } //=====存放地址完畢 //=====文件傳輸 //獲得文件上傳的流 InputStream inputStream = fileItem.getInputStream(); //創(chuàng)建一個(gè)文件輸出流 //realPath = 真實(shí)的文件夾 //差了一個(gè)文件,加上輸出的文件的名字+"/" +uuidFileName FileOutputStream fos = new FileOutputStream(realPath + "/" + fileName); //創(chuàng)建一個(gè)緩沖區(qū) byte[] buffer = new byte[1024 * 1024]; //判斷是否讀取完畢 int len = 0; //如果大于0說(shuō)明還存在數(shù)據(jù) while ((len = inputStream.read(buffer)) > 0) { fos.write(buffer, 0, len); } //關(guān)閉流 fos.close(); inputStream.close(); msg = "文件上傳成功!"; fileItem.delete();//上傳成功,清楚臨時(shí)文件 } } 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 測(cè)試結(jié)果
3. SpringMVC文件上傳和下載
3.1 上傳
在controller中有兩種方式
新建一個(gè)module,一套流程整體下來(lái)。測(cè)試能運(yùn)行即可
??>導(dǎo)入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"> <!-- 請(qǐng)求的編碼格式,必須和jSP的pageEncoding屬性一致,以便正確讀取表單的內(nèi)容,默認(rèn)為ISO-8859-1 --> <property name="defaultEncoding" value="utf-8"/> <!-- 上傳文件大小上限,單位為字節(jié)(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 對(duì)象 //批量上傳CommonsMultipartFile則為數(shù)組即可 @RequestMapping("/upload") public String fileUpload(@RequestParam("file") CommonsMultipartFile file , HttpServletRequest request) throws IOException { //獲取文件名 : file.getOriginalFilename(); String uploadFileName = file.getOriginalFilename(); //如果文件名為空,直接回到首頁(yè)! if ("".equals(uploadFileName)){ return "redirect:/index.jsp"; } System.out.println("上傳文件名 : "+uploadFileName); //上傳路徑保存設(shè)置 String path = request.getServletContext().getRealPath("/upload"); //如果路徑不存在,創(chuàng)建一個(gè) 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)); //文件輸出流 //讀取寫(xiě)出 int len=0; byte[] buffer = new byte[1024]; while ((len=is.read(buffer))!=-1){ os.write(buffer,0,len); os.flush(); } os.close(); is.close(); return "redirect:/index.jsp"; } /* * 采用file.Transto 來(lái)保存上傳的文件 */ @RequestMapping("/upload2") public String fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException { //上傳路徑保存設(shè)置 String path = request.getServletContext().getRealPath("/upload"); File realPath = new File(path); if (!realPath.exists()){ realPath.mkdir(); } //上傳文件地址 System.out.println("上傳文件保存地址:"+realPath); //通過(guò)CommonsMultipartFile的方法直接寫(xiě)文件(注意這個(gè)時(shí)候) file.transferTo(new File(realPath +"/"+ file.getOriginalFilename())); return "redirect:/index.jsp"; } }
??>測(cè)試:
3.2 下載
1、設(shè)置 response 響應(yīng)頭
2、讀取文件 – InputStream
3、寫(xiě)出文件 – OutputStream
4、執(zhí)行操作
5、關(guān)閉流 (先開(kāi)后關(guān))
??>index.jsp
<a href="${pageContext.request.contextPath}/download" rel="external nofollow" >點(diǎn)擊下載</a>
??>增加一個(gè)upload文件
并且把要下載的圖片弄進(jìn)去
??>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、設(shè)置response 響應(yīng)頭 response.reset(); //設(shè)置頁(yè)面不緩存,清空buffer response.setCharacterEncoding("UTF-8"); //字符編碼 response.setContentType("multipart/form-data"); //二進(jìn)制傳輸數(shù)據(jù) //設(shè)置響應(yīng)頭 response.setHeader("Content-Disposition", "attachment;fileName="+ URLEncoder.encode(fileName, "UTF-8")); File file = new File(path,fileName); //2、 讀取文件--輸入流 InputStream input=new FileInputStream(file); //3、 寫(xiě)出文件--輸出流 OutputStream out = response.getOutputStream(); byte[] buff =new byte[1024]; int index=0; //4、執(zhí)行 寫(xiě)出操作 while((index= input.read(buff))!= -1){ out.write(buff, 0, index); out.flush(); } out.close(); input.close(); return "ok"; }
??>測(cè)試:?
以上就是詳解JavaWeb如何實(shí)現(xiàn)文件上傳和下載功能的詳細(xì)內(nèi)容,更多關(guān)于JavaWeb文件上傳和下載的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- JavaWeb實(shí)現(xiàn)文件上傳功能詳解
- JavaWeb使用mvc模式實(shí)現(xiàn)登錄功能
- JavaWEB中Servlet的生命周期詳解
- java?web項(xiàng)目Session獲取不到問(wèn)題及解決
- 基于javaweb+jsp實(shí)現(xiàn)企業(yè)財(cái)務(wù)記賬管理系統(tǒng)
- Javaweb實(shí)戰(zhàn)之實(shí)現(xiàn)蛋糕訂購(gòu)系統(tǒng)
- 基于javaweb+jsp實(shí)現(xiàn)學(xué)生宿舍管理系統(tǒng)
- Java?WebService開(kāi)源框架CXF詳解
- Java webSerivce的使用看完你就明白了
相關(guān)文章
帶你了解Java數(shù)據(jù)結(jié)構(gòu)和算法之高級(jí)排序
這篇文章主要為大家介紹了Java數(shù)據(jù)結(jié)構(gòu)和算法之高級(jí)排序,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來(lái)幫助2022-01-01說(shuō)說(shuō)@ModelAttribute在父類(lèi)和子類(lèi)中的執(zhí)行順序
這篇文章主要介紹了@ModelAttribute在父類(lèi)和子類(lèi)中的執(zhí)行順序,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06Java如何獲取@TableField,@TableName注解的值
這篇文章主要介紹了Java如何獲取@TableField,@TableName注解的值,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01Java實(shí)現(xiàn)ArrayList排序的方法詳解
Java中常見(jiàn)的ArrayList排序方法主要為三種:JDK8的stream、Comparator#compare()和Comparable#compareTo(),本文將詳解這三者的使用,需要的可以參考一下2022-05-05淺談Java double 相乘的結(jié)果偏差小問(wèn)題
下面小編就為大家?guī)?lái)一篇淺談Java double 相乘的結(jié)果偏差小問(wèn)題。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-01-01