Java实现上传(支持多个文件同时上传)和下载
文件上传一直是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/beanshttp://www.springframework.org/schema/beans/spring-beans-4.2.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-4.2.xsdhttp://www.springframework.org/schema/txhttp://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>
以上变为文件上传和下载的全部代码,博主亲测过,没有问题。
Java实现上传(支持多个文件同时上传)和下载相关推荐
- element ui upload组件文件上传一次 后,不论是上传成功之后修改文件再上传还是上传失败重新上传,再次点击上传均无反应。
问题: Element UI Upload 组件文件上传一次 后,不论是上传成功之后修改文件再上传还是上传失败重新上传,再次点击上传均无反应. 原因: 第一次上传文件后,浏览器还保存着我们已经上传的文 ...
- plupload分片上传php,plupload 大文件分片上传与PHP分片合并探索
最近老大分给我了做一个电影cms系统,其中涉及到一个功能,使用七牛云的文件上传功能.七牛javascript skd,使用起来很方便,屏蔽了许多的技术细节.如果只满足与调用sdk,那么可能工作中也就没 ...
- java根据Freemarker模板渲染出Excel文件并在浏览器中下载
**java根据Freemarker模板渲染出Excel文件并在浏览器中下载** 准备工作 1.导入的依赖 2.创建模板 Freemrker语法大全: [Freemarker语法使用请点击该链接跳转学 ...
- java http 上传大文件上传_java实现大文件的上传
最近项目经理逼着让偶做树的展开,表嵌套表,可惜偶刚参加工作,水平低,这不在查资料嘛,可是不多久就传来了经理的叫嚣声,这么简单的东西,都一天了,你还没做完..................,哎真是郁闷 ...
- php文件上传代码_PHP实现文件分片上传的实例代码
PHP用超级全局变量数组$_FILES来记录文件上传相关信息的. 1.file_uploads=on/off 是否允许通过http方式上传文件 2.max_execution_time=30 允许脚本 ...
- jquery 分片上传php,jquery 大文件分片上传插件 fcup.js
软件介绍 fcup.js fcup 是一款支持大文件切片上传插件.该jquery插件使用简单,配置简单明了,支持上传类型指定,进度条查看上传进度.. 安装 直接下载源码,上传功能需要php环境,演示地 ...
- php文件如何上传到服务器,php文件怎么上传到云服务器
php文件怎么上传到云服务器 内容精选 换一换 当服务器A和服务器B同时挂载同一文件系统C时,在服务器A上传文件,服务器B同步此文件时存在延时,而单独上传至服务器B则没有延时.需要在两个服务器的挂载参 ...
- jquery 分片上传php,php 大文件分片上传
前端部分 上传 //上传控件 uploadBig('upload','zip,rar,7z,tar',{ id: '', type: 'upload_file', } ,(res)=>{ //t ...
- php切割文件上传,php+ajax实现文件切割上传功能示例
本文实例讲述了php+ajax实现文件切割上传功能.分享给大家供大家参考,具体如下: html5中的file对象继承blob二进制对象,blob提供了一个slice函数,可以用来切割文件数据. var ...
最新文章
- docker部署minio
- SharePoint 2013 表单认证使用ASP.Net配置工具添加用户
- 推荐系统笔记:Introduction
- Java数据结构和算法(八)——递归
- Python正则表达式-常用函数的基本使用
- SQL Server 2008带字段注释导入Power Designer 9.5
- MVC和MVVM以及MVP的介绍
- 剑指offer(21):栈的压入、弹出序列
- spring定时任务详解(@Scheduled注解)多线程讲解
- linux在主函数中调用进程,linux 调用进程
- 【python 6】Numpy
- 取消数据源的自动创建,使用Seata对数据源进行代理
- python lambda map reduce_简单了解python filter、map、reduce的区别
- Mac OS X下安装Java 7及配置Eclipse JDK
- ionic 父子组件传值
- Helm 3 完整教程(二十四):创建和使用子 chart
- Windows Moible, Wince 使用.NET Compact Framework的进行蓝牙(Bluetooth)广播程序的开发
- php 485通讯协议 编程,485通讯协议程序怎么写(51单片机的485通信程序案例)
- css样式实现居中对齐
- 即日起,发放三种勋章公告。
热门文章
- 人的一生可能燃烧也可能腐朽,我不能腐朽,我愿意燃烧起来!熬过去了,你就能看到一个全新的自己...
- navicat premium连接数据库出现2059错误
- ECDH密钥交换的C程序
- c/c++位操作简介--移位、位与、位或、异或
- AOSP 8.0 系统启动之四ART虚拟机启动(一)
- 永中科技是怎样被裁定破产的?
- 北大计算机科学与技术保研率,北京师范大学2019届保研率34.7%,北大、人大、清华外校深造前三...
- CAP定理与BASE理论
- Rainbow的站点流量统计分析
- [20150901]提示USE_CONCAT.txt