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中下载文件并保存在本地指定路径中. 服务器不需要打包. 支持大文件断点下载.比如下 ...
随机推荐
- (五)mybatis-spring的集成
mybatis-spring的集成 源码下载(数据库使用derby,具体数据库结构参考这里) 在src下新建applicationContext.xml 配置内容:数据源.SqlSessionFact ...
- Git相关命令总结
准备类型命令 生成ssh秘钥(密码可以留空): ssh-keygen 配置用户信息(安装后第一件事): # --systen代表配置系统全局,--global代表配置当前用户全局# 在当前项目中使用其 ...
- flutter 入门(Mac)
背景 近一年时间都在用 React Native 开发公司的 APP,水平基本上可以说是登堂入室了.前一段时间兴起一阵 Flutter 热,后端的同事都有推荐,今年 Google 大会又推出 flut ...
- Solr查询配置及优化【eDisMax查询解析器】
一.简介 Lucene查询解析器语法支持创建任意复杂的布尔查询,但还有一些缺点,它不是用户查询处理的理想解决方案.这里面最大的问题是Lucene查询解析器的语法要求严格,一旦破坏就会抛出异常.指望用户 ...
- 浅谈ConcurrentDictionary与Dictionary
在.NET4.0之前,如果我们需要在多线程环境下使用Dictionary类,除了自己实现线程同步来保证线程安全外,我们没有其他选择.很多开发人员肯定都实现过类似的线程安全方案,可能是通过创建全新的线程 ...
- iOS中的分类和扩展
一.什么是分类? 概念:分类(Category)是OC中的特有语法,它是表示一个指向分类的结构体指针.根据下面源码组成可以看到它没有属性列表,原则上是不能添加成员变量(其实可以借助运行时功能,进行关联 ...
- 不要忽视Managed code stripping的副作用
0x00 前言 Unity 2018.3之后,新的“Managed Stripping Level”选项将替换 player settings 中原有的“Stripping Level”选项. 这个新 ...
- 8421BCD转余3码Verilog HDL的设计(1)
近期阅读Verilog HDL高级数字设计(第二版)中,遇到了串行比特流BCD码转余3码转换器的设计,比较独特的是: (1)该转换器的输入为1位串行比特流,输出也为1位串行比特流. BCD码与余三码的 ...
- css手写一个表头固定
Bootstrap,layui等前端框架里面都对表头固定,表格滚动有实现,偏偏刚入职的公司选择了手动渲染表格,后期又觉得表格数据拉太长想要做表头固定.为了避免对代码改动太大,所以决定手写表头固定 主要 ...
- java多线程基础API
本次内容主要讲认识Java中的多线程.线程的启动与中止.yield()和join.线程优先级和守护线程. 1.Java程序天生就是多线程的 一个Java程序从main()方法开始执行,然后按照既定的代 ...