Java實(shí)現(xiàn)上傳和下載功能(支持多個(gè)文件同時(shí)上傳)
文件上傳一直是Web項(xiàng)目中必不可少的一項(xiàng)功能。
項(xiàng)目結(jié)構(gòu)如下:(這是我之前創(chuàng)建的SSM整合的框架項(xiàng)目,在這上面添加文件上傳與下載)
主要的是FileUploadController,doupload.jsp,up.jsp,springmvc.xml
1.先編寫(xiě)up.jsp
<form action="doupload.jsp" enctype="multipart/form-data" method="post"> <p>上傳者:<input type="text" name="user"></p> <p>選擇文件:<input type="file" name="nfile"></p> <p>選擇文件:<input type="file" name="nfile1"></p> <p><input type="submit" value="提交"></p> </form>
以上便是up.jsp的核心代碼;
2.編寫(xiě)doupload.jsp
<% request.setCharacterEncoding("utf-8"); String uploadFileName = ""; //上傳的文件名 String fieldName = ""; //表單字段元素的name屬性值 //請(qǐng)求信息中的內(nèi)容是否是multipart類(lèi)型 boolean isMultipart = ServletFileUpload.isMultipartContent(request); //上傳文件的存儲(chǔ)路徑(服務(wù)器文件系統(tǒng)上的絕對(duì)文件路徑) String uploadFilePath = request.getSession().getServletContext().getRealPath("upload/" ); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { //解析form表單中所有文件 List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { //依次處理每個(gè)文件 FileItem item = (FileItem) iter.next(); if (item.isFormField()){ //普通表單字段 fieldName = item.getFieldName(); //表單字段的name屬性值 if (fieldName.equals("user")){ //輸出表單字段的值 out.print(item.getString("UTF-8")+"上傳了文件。<br/>"); } }else{ //文件表單字段 String fileName = item.getName(); if (fileName != null && !fileName.equals("")) { File fullFile = new File(item.getName()); File saveFile = new File(uploadFilePath, fullFile.getName()); item.write(saveFile); uploadFileName = fullFile.getName(); out.print("上傳成功后的文件名是:"+uploadFileName); out.print("\t\t下載鏈接:"+"<a href='download.action?name="+uploadFileName+"'>"+uploadFileName+"</a>"); out.print("<br/>"); } } } } catch (Exception e) { e.printStackTrace(); } } %>
該頁(yè)面主要是內(nèi)容是,通過(guò)解析request,并設(shè)置上傳路徑,創(chuàng)建一個(gè)迭代器,先進(jìn)行判空,再通過(guò)循環(huán)來(lái)實(shí)現(xiàn)多個(gè)文件的上傳,再輸出文件信息的同時(shí)打印文件下載路徑。
效果圖:
3.編寫(xiě)FilterController實(shí)現(xiàn)文件下載的功能(相對(duì)上傳比較簡(jiǎn)單):
@Controller public class FileUploadController { @RequestMapping(value="/download") public ResponseEntity<byte[]> download(HttpServletRequest request,HttpServletResponse response,@RequestParam("name") String filename)throws Exception { //下載顯示的文件名,解決中文名稱(chēng)亂碼問(wèn)題 filename=new String(filename.getBytes("iso-8859-1"),"UTF-8"); //下載文件路徑 String path = request.getServletContext().getRealPath("/upload/"); File file = new File(path + File.separator + filename); HttpHeaders headers = new HttpHeaders(); //下載顯示的文件名,解決中文名稱(chēng)亂碼問(wèn)題 String downloadFielName = new String(filename.getBytes("iso-8859-1"),"UTF-8"); //通知瀏覽器以attachment(下載方式)打開(kāi)圖片 headers.setContentDispositionFormData("Content-Disposition", downloadFielName); //application/octet-stream : 二進(jìn)制流數(shù)據(jù)(最常見(jiàn)的文件下載)。 headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED); } }
4.實(shí)現(xiàn)上傳文件的功能還需要在springmvc中配置bean:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 上傳文件大小上限,單位為字節(jié)(10MB) --> <property name="maxUploadSize"> <value>10485760</value> </property> <!-- 請(qǐng)求的編碼格式,必須和jSP的pageEncoding屬性一致,以便正確讀取表單的內(nèi)容,默認(rèn)為ISO-8859-1 --> <property name="defaultEncoding"> <value>UTF-8</value> </property> </bean>
完整代碼如下:
up.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>File控件</title> </head> <body> <form action="doupload.jsp" enctype="multipart/form-data" method="post"> <p>上傳者:<input type="text" name="user"></p> <p>選擇文件:<input type="file" name="nfile"></p> <p>選擇文件:<input type="file" name="nfile1"></p> <p><input type="submit" value="提交"></p> </form> </body> </html>
doupload.jsp
<%@ page language="java" pageEncoding="UTF-8"%> <%@page import="java.io.*,java.util.*"%> <%@page import="org.apache.commons.fileupload.*"%> <%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory" %> <%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>上傳處理頁(yè)面</title> </head> <body> <% request.setCharacterEncoding("utf-8"); String uploadFileName = ""; //上傳的文件名 String fieldName = ""; //表單字段元素的name屬性值 //請(qǐng)求信息中的內(nèi)容是否是multipart類(lèi)型 boolean isMultipart = ServletFileUpload.isMultipartContent(request); //上傳文件的存儲(chǔ)路徑(服務(wù)器文件系統(tǒng)上的絕對(duì)文件路徑) String uploadFilePath = request.getSession().getServletContext().getRealPath("upload/" ); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { //解析form表單中所有文件 List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { //依次處理每個(gè)文件 FileItem item = (FileItem) iter.next(); if (item.isFormField()){ //普通表單字段 fieldName = item.getFieldName(); //表單字段的name屬性值 if (fieldName.equals("user")){ //輸出表單字段的值 out.print(item.getString("UTF-8")+"上傳了文件。<br/>"); } }else{ //文件表單字段 String fileName = item.getName(); if (fileName != null && !fileName.equals("")) { File fullFile = new File(item.getName()); File saveFile = new File(uploadFilePath, fullFile.getName()); item.write(saveFile); uploadFileName = fullFile.getName(); out.print("上傳成功后的文件名是:"+uploadFileName); out.print("\t\t下載鏈接:"+"<a href='download.action?name="+uploadFileName+"'>"+uploadFileName+"</a>"); out.print("<br/>"); } } } } catch (Exception e) { e.printStackTrace(); } } %> </body> </html>
FileUploadController.java
package ssm.me.controller; import java.io.File; import java.net.URLDecoder; import java.util.Iterator; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.FileUtils; import org.junit.runners.Parameterized.Parameter; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; @Controller public class FileUploadController { @RequestMapping(value="/download") public ResponseEntity<byte[]> download(HttpServletRequest request,HttpServletResponse response,@RequestParam("name") String filename)throws Exception { //下載顯示的文件名,解決中文名稱(chēng)亂碼問(wèn)題 filename=new String(filename.getBytes("iso-8859-1"),"UTF-8"); //下載文件路徑 String path = request.getServletContext().getRealPath("/upload/"); File file = new File(path + File.separator + filename); HttpHeaders headers = new HttpHeaders(); //下載顯示的文件名,解決中文名稱(chēng)亂碼問(wèn)題 String downloadFielName = new String(filename.getBytes("iso-8859-1"),"UTF-8"); //通知瀏覽器以attachment(下載方式)打開(kāi)圖片 headers.setContentDispositionFormData("Content-Disposition", downloadFielName); //application/octet-stream : 二進(jìn)制流數(shù)據(jù)(最常見(jiàn)的文件下載)。 headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED); } }
SpringMVC.xml(僅供參考,有的地方不可以照搬)
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 一個(gè)用于自動(dòng)配置注解的注解配置 --> <mvc:annotation-driven></mvc:annotation-driven> <!-- 掃描該包下面所有的Controller --> <context:component-scan base-package="ssm.me.controller"></context:component-scan> <!-- 視圖解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"></bean> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 上傳文件大小上限,單位為字節(jié)(10MB) --> <property name="maxUploadSize"> <value>10485760</value> </property> <!-- 請(qǐng)求的編碼格式,必須和jSP的pageEncoding屬性一致,以便正確讀取表單的內(nèi)容,默認(rèn)為ISO-8859-1 --> <property name="defaultEncoding"> <value>UTF-8</value> </property> </bean> </beans>
web.xml(僅供參考,有的地方不可以照搬)
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>Student</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 初始化參數(shù) --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/applicationContext-*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> </web-app>
以上便為文件上傳和下載的全部代碼,博主親測(cè)過(guò),沒(méi)有問(wèn)題。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot添加自定義攔截器的實(shí)現(xiàn)代碼
這篇文章主要介紹了SpringBoot添加自定義攔截器的實(shí)現(xiàn)代碼,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-09-09java數(shù)組與以逗號(hào)分隔開(kāi)的字符串的相互轉(zhuǎn)換操作
這篇文章主要介紹了java數(shù)組與以逗號(hào)分隔開(kāi)的字符串的相互轉(zhuǎn)換操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-09-09Idea 2020.2 創(chuàng)建web、Spring項(xiàng)目的教程圖解
這篇文章主要介紹了Idea 2020.2 創(chuàng)建web、Spring項(xiàng)目的教程,本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-08-08Java實(shí)現(xiàn)HashMap排序方法的示例詳解
這篇文章主要通過(guò)一些示例為大家介紹了Java對(duì)HashMap進(jìn)行排序的方法,幫助大家更好的理解和使用Java,感興趣的朋友可以了解一下2022-05-05淺談java中null是什么,以及使用中要注意的事項(xiàng)
下面小編就為大家?guī)?lái)一篇淺談java中null是什么,以及使用中要注意的事項(xiàng)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-09-09詳解Java如何在業(yè)務(wù)代碼中優(yōu)雅的使用策略模式
這篇文章主要為大家介紹了Java如何在業(yè)務(wù)代碼中優(yōu)雅的使用策略模式,文中的示例代碼講解詳細(xì),具有一定的學(xué)習(xí)價(jià)值,感興趣的可以了解下2023-08-08java使用正則表達(dá)為數(shù)字添加千位符的簡(jiǎn)單方法
這篇文章主要介紹了java使用正則表達(dá)為數(shù)字添加千位符的簡(jiǎn)單方法,需要的朋友可以參考下2014-04-04springboot?aop里的@Pointcut()的配置方式
這篇文章主要介紹了springboot?aop里的@Pointcut()的配置方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11