Java实现上传和下载功能(支持多个文件同时上传)
程序员文章站
2022-03-15 08:13:26
文件上传一直是web项目中必不可少的一项功能。项目结构如下:(这是我之前创建的ssm整合的框架项目,在这上面添加文件上传与下载)主要的是fileuploadcontroller,doupload.js...
文件上传一直是web项目中必不可少的一项功能。
项目结构如下:(这是我之前创建的ssm整合的框架项目,在这上面添加文件上传与下载)
主要的是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属性值 //请求信息中的内容是否是multipart类型 boolean ismultipart = servletfileupload.ismultipartcontent(request); //上传文件的存储路径(服务器文件系统上的绝对文件路径) 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()) { //依次处理每个文件 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(); } } %>
该页面主要是内容是,通过解析request,并设置上传路径,创建一个迭代器,先进行判空,再通过循环来实现多个文件的上传,再输出文件信息的同时打印文件下载路径。
效果图:
3.编写filtercontroller实现文件下载的功能(相对上传比较简单):
@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 : 二进制流数据(最常见的文件下载)。 headers.setcontenttype(mediatype.application_octet_stream); return new responseentity<byte[]>(fileutils.readfiletobytearray(file), headers, httpstatus.created); } }
4.实现上传文件的功能还需要在springmvc中配置bean:
<bean id="multipartresolver" class="org.springframework.web.multipart.commons.commonsmultipartresolver"> <!-- 上传文件大小上限,单位为字节(10mb) --> <property name="maxuploadsize"> <value>10485760</value> </property> <!-- 请求的编码格式,必须和jsp的pageencoding属性一致,以便正确读取表单的内容,默认为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属性值 //请求信息中的内容是否是multipart类型 boolean ismultipart = servletfileupload.ismultipartcontent(request); //上传文件的存储路径(服务器文件系统上的绝对文件路径) 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()) { //依次处理每个文件 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 : 二进制流数据(最常见的文件下载)。 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"> <!-- 一个用于自动配置注解的注解配置 --> <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"> <!-- 上传文件大小上限,单位为字节(10mb) --> <property name="maxuploadsize"> <value>10485760</value> </property> <!-- 请求的编码格式,必须和jsp的pageencoding属性一致,以便正确读取表单的内容,默认为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> <!-- 初始化参数 --> <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>
以上便为文件上传和下载的全部代码,博主亲测过,没有问题。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。