SpringMVC框架——文件的上传与下载
使用SpringMVC框架做个小练习,需求:
1、单个图片上传并显示到页面中;
2、多个图片上传并显示到页面中;
3、上传文件后下载文件;
1、pom.xml中添加依赖
<!-- 文件上传 --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency> <!--jstl--> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies>
2、编写JSP页面
- input 的 type 设置为 file
- form 表单的 method 设置为 post
- form 表单的 enctype 设置为 multipart/form-data
- 单文件上传页面upload.jsp
<!DOCTYPE html> <%@ page contentType="text/html; charset=UTF-8" language="java" %> <%@ page isELIgnored="false" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/upload" method="post" enctype="multipart/form-data"> <input type="file" name="img"/> <input type="submit" value="上传"/><br/><br/> <c:if test="${filePath!=null && filePath!=''}"> 上传成功 <a href="/download?filePath=${filePath}">下载</a> </c:if> </form> </body> </html>
- 多文件上传页面uploadMore.jsp
<!DOCTYPE html> <%@ page contentType="text/html; charset=UTF-8" language="java" %> <%@ page isELIgnored="false" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/uploadMore" method="post" enctype="multipart/form-data"> file1:<input type="file" name="imgs"/> file2:<input type="file" name="imgs"/> file3:<input type="file" name="imgs"/> <input type="submit" value="上传"/><br/> <c:if test="${filePath!=null && filePath!=''}"> <h1>上传的图片</h1> <c:forEach items="${filePaths}" var="img"> <img src="${img}" style="width: 300px;"> </c:forEach> </c:if> </form> </body> </html>
3、编写controller
package com.sunjian.controller; import org.apache.commons.io.FileUtils; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import java.io.*; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @author sunjian * @date 2020/3/20 8:07 */ @Controller public class UploadController { @RequestMapping("/upload") public String upload(@RequestParam("img")MultipartFile img, HttpServletRequest request){ if(img.getSize() > 0){ // 获取target目录下的文件保存路径 String path = (String) request.getSession().getServletContext().getRealPath("files"); String fileName = img.getOriginalFilename();// 获取原始文件名 File file = new File(path, fileName); // 创建空文件 try { img.transferTo(file); // 将img中的内容转移到file这个空文件中 } catch (IOException e) { e.printStackTrace(); } request.setAttribute("filePath", "/files/"+fileName); } return "upload"; } @RequestMapping("/uploadMore") public String uploadMore(@RequestParam("imgs") MultipartFile[] imgs, HttpServletRequest request){ List<String> filePaths = new ArrayList<>(); for(MultipartFile img:imgs){ if(img.getSize() > 0){ String path = request.getSession().getServletContext().getRealPath("files"); String fileName = img.getOriginalFilename(); File file = new File(path, fileName);// 创建文件 try { img.transferTo(file); filePaths.add("/files/" + fileName); // 将文件路径添加到list中 } catch (IOException e) { e.printStackTrace(); } } } request.setAttribute("filePaths", filePaths); return "uploadMore"; } @RequestMapping("/download") public void download(String filePath, HttpServletRequest request, HttpServletResponse response){ // 文件名处理 filePath = filePath.split("/")[2]; // 设置响应流文件进行下载 response.setHeader("Content-Disposition", "attachment;filename=" + filePath); try { ServletOutputStream servletOutputStream = response.getOutputStream(); File file = new File(request.getSession().getServletContext().getRealPath("files"), filePath); byte[] bytes = FileUtils.readFileToByteArray(file); servletOutputStream.write(bytes); servletOutputStream.flush(); servletOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
4、在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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> <!-- 配置自动扫描 --> <context:component-scan base-package="com.sunjian"></context:component-scan> <!-- 配置视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- 消息转换器 --> <mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"></bean> </mvc:message-converters> </mvc:annotation-driven> <!-- 自定义数据类型转换器 --> <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <list> <bean class="com.sunjian.converter.DataConverter"> <constructor-arg type="java.lang.String" value="yyyy-MM-dd"></constructor-arg> </bean> <bean class="com.sunjian.converter.goodsConverter"></bean> </list> </property> </bean> <!--文件上传--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 处理文件名中文乱码 --> <property name="defaultEncoding" value="utf-8"></property> <!-- 多文件上传总⼤小的上限 100M --> <property name="maxUploadSize" value="104857600"></property> <!-- 单文件大小的上限 10M --> <property name="maxUploadSizePerFile" value="10485760"></property> </bean> <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven> </beans>
5、启动项目,访问页面上传图片
http://localhost:7777/upload.jsp
http://localhost:7777/uploadMore.jsp
下载
OK.
SpringMVC框架——文件的上传与下载的更多相关文章
- 使用springmvc进行文件的上传和下载
文件的上传 SpringMVC支持文件上传组件,commons-fileupload,commons-fileupload依赖commons-io组件 配置步骤说明 第一步:导入包 commons-f ...
- SpringMVC 实现文件的上传与下载
一 配置SpringMVC ,并导入与文件上传下载有关的jar包(在此不再赘述) 二 新建 相应 jsp 和controller FileUpAndDown.jsp <%@ page lang ...
- SpringMVC下文件的上传与下载以及文件列表的显示
1.配置好SpringMVC环境-----SpringMVC的HelloWorld快速入门! 导入jar包:commons-fileupload-1.3.1.jar和commons-io-2.4.ja ...
- springMVC实现文件的上传和下载
文件的下载功能 @RequestMapping("/testDown")public ResponseEntity<byte[]> testResponseEntity ...
- 基于struts2框架文件的上传与下载
在开发一些社交网站时,需要有允许用户上传自己本地文件的功能,则需要文件的上传下载代码. 首先考虑的是文件的储存位置,这里不考虑存在数据库,因为通过数据库查询获取十分消耗资源与时间,故需将数据存储在服务 ...
- Spring MVC 实现文件的上传和下载
前些天一位江苏经贸的学弟跟我留言问了我这样一个问题:“用什么技术来实现一般网页上文件的上传和下载?是框架还是Java中的IO流”.我回复他说:“使用Spring MVC框架可以做到这一点,因为Spri ...
- 在SpringMVC框架下实现文件的 上传和 下载
在eclipse中的javaEE环境下:导入必要的架包 web.xml的配置文件: <?xml version="1.0" encoding="UTF-8" ...
- 文件的上传和下载--SpringMVC
文件的上传和下载是项目开发中最常用的功能,例如图片的上传和下载.邮件附件的上传和下载等. 接下来,将对Spring MVC环境中文件的上传和下载进行详细的讲解. 一.文件上传 多数文件上传都是通过表单 ...
- SpringMVC+Ajax实现文件批量上传和下载功能实例代码
需求: 文件批量上传,支持断点续传. 文件批量下载,支持断点续传. 使用JS能够实现批量下载,能够提供接口从指定url中下载文件并保存在本地指定路径中. 服务器不需要打包. 支持大文件断点下载.比如下 ...
随机推荐
- [洛谷P4777] [模板] 扩展中国剩余定理
扩展中国剩余定理,EXCRT. 题目传送门 重温一下中国剩余定理. 中国剩余定理常被用来解线性同余方程组: x≡a[1] (mod m[1]) x≡a[2] (mod m[2]) ...... x≡a ...
- Replace into 与Insert into on duplicate key update的区别
前提条件:除非表有一个PRIMARY KEY或UNIQUE索引,否则,使用这2条语句没有意义.该语句会与INSERT相同 1. Replace into (1) 添加相同的主键 操作前 ...
- 双股同时上市!小米IPO是想要玩场大的?
近日,据相关媒体报道,有相关人士称小米IPO最终可能敲定A+H股两地发行.但目前还未得到小米官方证实.此前关于小米要上市的消息已经流传已久了,从雷军刚开始的矢口否认到后来的默认,再到后来相关消息愈来 ...
- SWUST OJ NBA Finals(0649)
NBA Finals(0649) Time limit(ms): 1000 Memory limit(kb): 65535 Submission: 404 Accepted: 128 Descri ...
- Catalan母函数法解表达式
- CSS 之动态变换背景颜色
先上效果图 HTML代码: 123456789 <div class="header"> <h1>GCCHRN'S BLOG</h1> < ...
- flask_admin+flask_login 整合,jieba分词+echarts数据分析可视化
项目地址: https://github.com/WES6/list
- QQ公众号出炉 同门相争意欲何为
同门相争意欲何为"> 当初腾讯大张旗鼓地推出微信时,很多业内人士都认为其与QQ在功能.用户等方面多有重叠,肯定会阻碍QQ的发展和微信的成长.没想到,二者避重就轻地在不同的侧重点发展,反 ...
- 解密JDK8 枚举
写一个枚举类 1 2 3 4 5 6 public enum Season { SPRING, SUMMER, AUTUMN, WINTER } 然后我们使用javac编译上面的类,得到class文件 ...
- Hellc
[题目描述] 作为一个生活散漫的人,小 Z 每天早上都要耗费很久从一堆五颜六色的袜子中找出一双来穿.终于有一天,小 Z 再也无法忍受这恼人的找袜子过程,于是他决定听天由命-- 具体来说,小 Z 把这 ...