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.先編寫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.編寫doupload.jsp
<%
request.setCharacterEncoding("utf-8");
String uploadFileName = ""; //上傳的文件名
String fieldName = ""; //表單字段元素的name屬性值
//請(qǐng)求信息中的內(nèi)容是否是multipart類型
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();
}
}
%>
該頁面主要是內(nèi)容是,通過解析request,并設(shè)置上傳路徑,創(chuàng)建一個(gè)迭代器,先進(jìn)行判空,再通過循環(huán)來實(shí)現(xiàn)多個(gè)文件的上傳,再輸出文件信息的同時(shí)打印文件下載路徑。
效果圖:


3.編寫FilterController實(shí)現(xiàn)文件下載的功能(相對(duì)上傳比較簡單):
@Controller
public class FileUploadController {
@RequestMapping(value="/download")
public ResponseEntity<byte[]> download(HttpServletRequest request,HttpServletResponse response,@RequestParam("name") String filename)throws Exception {
//下載顯示的文件名,解決中文名稱亂碼問題
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();
//下載顯示的文件名,解決中文名稱亂碼問題
String downloadFielName = new String(filename.getBytes("iso-8859-1"),"UTF-8");
//通知瀏覽器以attachment(下載方式)打開圖片
headers.setContentDispositionFormData("Content-Disposition", downloadFielName);
//application/octet-stream : 二進(jìn)制流數(shù)據(jù)(最常見的文件下載)。
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>上傳處理頁面</title>
</head>
<body>
<%
request.setCharacterEncoding("utf-8");
String uploadFileName = ""; //上傳的文件名
String fieldName = ""; //表單字段元素的name屬性值
//請(qǐng)求信息中的內(nèi)容是否是multipart類型
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 {
//下載顯示的文件名,解決中文名稱亂碼問題
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();
//下載顯示的文件名,解決中文名稱亂碼問題
String downloadFielName = new String(filename.getBytes("iso-8859-1"),"UTF-8");
//通知瀏覽器以attachment(下載方式)打開圖片
headers.setContentDispositionFormData("Content-Disposition", downloadFielName);
//application/octet-stream : 二進(jìn)制流數(shù)據(jù)(最常見的文件下載)。
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è)過,沒有問題。
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
MyBatis配置文件解析與MyBatis實(shí)例演示
這篇文章主要介紹了MyBatis配置文件解析與MyBatis實(shí)例演示以及怎樣編譯安裝MyBatis,需要的朋友可以參考下2022-04-04
spring?retry方法調(diào)用失敗重試機(jī)制示例解析
這篇文章主要為大家介紹了spring?retry方法調(diào)用失敗重試機(jī)制的示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2022-03-03
java -jar后臺(tái)啟動(dòng)的四種方式小結(jié)
這篇文章主要介紹了java -jar后臺(tái)啟動(dòng)的四種方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-09-09
Java并發(fā)編程之CountDownLatch原理詳解
這篇文章主要介紹了Java并發(fā)編程之CountDownLatch原理詳解,CountDownLatch類中使用了一個(gè)繼承自AQS的共享鎖Sync對(duì)象,構(gòu)造CountDownLatch對(duì)象時(shí)會(huì)將傳入的線程數(shù)值設(shè)為AQS的state值,需要的朋友可以參考下2023-12-12
Java實(shí)現(xiàn)設(shè)計(jì)模式之責(zé)任鏈模式
責(zé)任鏈模式是一種行為設(shè)計(jì)模式,允許你將請(qǐng)求沿著處理鏈發(fā)送,然后處理者都可對(duì)其進(jìn)行處理,完成后可以再將其傳遞給下一個(gè)處理者。下面將會(huì)舉例說明什么是責(zé)任鏈模式,責(zé)任鏈模式該如何使用2022-08-08

