springMvc之文件上传与下载
我们经常会使用的一个功能是文件下载,既然有文件下载就会有文件上传,下面我们来看一下文件上传是如何实现的
首先准备好一个页面
<style type="text/css">
form{
margin:0px auto;
border:1px solid red;
width:500px;
padding:20px;
}
</style>
</head> <body>
<form action="${pageContext.request.contextPath }/frist.do" method="post" enctype="multipart/form-data">
<h1>文件上传</h1>
文件:<input type="file" name="uploadFile"/><br/>
文件:<input type="file" name="uploadFile"/><br/>
文件:<input type="file" name="uploadFile"/><br/>
<input type="submit" value="上传">
</form>
</body>
单文件上传
通过对文件的大小来判断是否有文件
通过文件的类型来判断是否是允许
@Controller
public class MyController {
@RequestMapping(value="/frist.do", method=RequestMethod.POST)
public String doFirst(HttpSession session,MultipartFile uploadFile)throws Exception{
if(uploadFile.getSize()>0){
//02.获取前半部分路径,jiangWebRoot下一个名称为images文件夹 转换成绝对路径
String path = session.getServletContext().getRealPath("/upload");
//01.获取文件名作为保存到服务器的文件名称
String fileName=uploadFile.getOriginalFilename();
if(fileName.endsWith(".jpg")||fileName.endsWith(".JPG")){
//03.路径拼接
File file = new File(path,fileName);
uploadFile.transferTo(file);
}
return "welcome.jsp";
}
return "error.jsp";
}
applicationContext.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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
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/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
"> <!-- 配置包扫描器 -->
<context:component-scan base-package="cn.controller"></context:component-scan> <bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property><!-- 客户端发送数据的编码 -->
<property name="maxUploadSize" value="5242880"></property><!-- 上传文件的大小 -->
<!-- <property name="uploadTempDir" value="/upload"></property> -->
</bean>
<!-- mvc注解驱动 -->
<mvc:annotation-driven /> </beans>
web.xml
<!--?xml version="1.0" encoding="UTF-8"?-->
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name></display-name>
<!-- ================spring mvc 适配器================ -->
<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:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!-- ================================================== --> <welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
多文件上传(多文件上传与单文件上传配置相同下面介绍一下不同的地方)
标记为红色的字段为多文件上传 与单文件上传的区别
@RequestMapping(value="/firstdown.do")
public String doFirst(@RequestParam MultipartFile[] uploadFile,HttpSession session)throws Exception{
for (MultipartFile item : uploadFile) { if(item.getSize()>0){
//02.获取前半部分路径,jiangWebRoot下一个名称为images文件夹 转换成绝对路径
String path = session.getServletContext().getRealPath("/upload");
//01.获取文件名作为保存到服务器的文件名称
String fileName=item.getOriginalFilename();
if(fileName.endsWith(".jpg")||fileName.endsWith(".JPG")){
//03.路径拼接
File file = new File(path,fileName);
item.transferTo(file);
}
return "welcome.jsp";
}
}
return "error.jsp";
}
文件下载
<br> public static void download(HttpServletRequest request,
HttpServletResponse response, String storeName, String contentType
) throws Exception { request.setCharacterEncoding("UTF-8");
BufferedInputStream bis = null;
BufferedOutputStream bos = null; //获取项目根目录
String ctxPath = request.getSession().getServletContext()
.getRealPath(""); //获取下载文件露肩
String downLoadPath = ctxPath+"/uploadFile/"+ storeName; //获取文件的长度
long fileLength = new File(downLoadPath).length(); //设置文件输出类型
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment; filename="
+ new String(storeName.getBytes("utf-8"), "ISO8859-1"));
//设置输出长度
response.setHeader("Content-Length", String.valueOf(fileLength));
//获取输入流
bis = new BufferedInputStream(new FileInputStream(downLoadPath));
//输出流
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
//关闭流
bis.close();
bos.close();
}
下载直接访问控制器如:http:\\localhost:8080/springmvc/download.do
或者通过JSP页面
<a href="./downloadFile/download" >下载</a>
springMvc之文件上传与下载的更多相关文章
- SpringMVC 实现文件上传与下载,并配置异常页面
		目录 上传文件的表单要求 Spring MVC实现上传文件 需要导入的jar包 配置MultipartResolver解析器 编写接收上传文件的控制器 Spring MVC实现文件下载 下载文件时的h ... 
- 使用springMVC实现文件上传和下载之环境配置与上传
		最近的项目中用到了文件的上传和下载功能,任务分配给了其他的同时完成.如今项目结束告一段落,我觉着这个功能比较重要,因此特意把它提取出来自己进行了尝试. 一. 基础配置: maven导包及配置pom.x ... 
- springmvc之文件上传、下载
		1.接收到的是图片的流时 //上传头像 @RequestMapping(value = "/uploadHeadSculpture", method = RequestMethod ... 
- SpringMVC的文件上传与下载
		1. 单文件上传 配置jsp页面 <%@ page contentType="text/html;charset=UTF-8" language="java&quo ... 
- 使用SpringMVC实现文件上传和下载
		文件上传 第一步,加入jar包: commons-fileupload-1.3.1.jar commons-io-2.4.jar 第二步,在SpringMVC配置文件中配置CommonsMultipa ... 
- 【SpringMVC】文件上传与下载、拦截器、异常处理器
		文件下载 使用ResponseEntity实现下载文件的功能 index.html <!DOCTYPE html> <html lang="en" xmlns:t ... 
- 使用springMVC实现文件上传和下载之文件下载
		接上一篇,文件下载需要获取下载文件的存储路径,这里只是手动填入,如果是在具体项目中,可以把文件名和上传后的存储路径保存在数据库中.然后增加一个文件列表的页面展示文件名和文件路径,然后点击下载的时候把相 ... 
- 文件上传和下载(可批量上传)——Spring(二)
		针对SpringMVC的文件上传和下载.下载用之前“文件上传和下载——基础(一)”的依然可以,但是上传功能要修改,这是因为springMVC 都为我们封装好成自己的文件对象了,转换的过程就在我们所配置 ... 
- 使用Spring MVC实现文件上传与下载
		前段时间做毕业设计的时候,想要完成一个上传文件的功能,后来,虽然在自己本地搭建了一个ftp服务器,然后使用公司的工具完成了一个文档管理系统:但是还是没有找到自己想要的文件上传与下载的方式. 今天看到一 ... 
随机推荐
- Chapter 3 Phenomenon——20
			"All I know is that you weren't anywhere near me — 所有我知道的就是你当时不在我旁边的任何地方—— Tyler didn't see you ... 
- Spring总结 4.AOP之为对象添加新功能
			Spring除了提供增强原有功能的方法外,还提供了为一个对象引入新功能的方法.如下: package cn.powerfully.service; public interface IService ... 
- Python面试题目--汇总
			原文链接-https://github.com/taizilongxu/interview_python Python语言特性 1 Python的函数参数传递 2 Python中的元类(metacla ... 
- React多页面应用脚手架-v1.3.0
			react-multi-page-app是一个基于react和webpack的多页面应用架构,通过编译生成对应目录结构清晰的静态页面,实现多页面便捷开发维护.1.3.0 版本对项目整体做了一个全面的升 ... 
- 树莓派安装.net core 2.1
			0.更新源 sudo apt-get update 1.安装依赖 sudo apt-get install curl libunwind8 gettext 2.下载 SDK 或者 RunTime ht ... 
- 调用百度api输出地址和城市查询出具体坐标系
			在工作中遇到标题的内容,不知道如何写,后来我的领导写了一套代码,感觉很是厉害,特在此收藏,留作纪念 public static string GetResponse(string address, s ... 
- hadoop 用户
			上篇文章说过,hadoop实际上就是就是一个liunx虚拟机,它的文件操作命令同linux,而它的用户呢?它的用户实际上就是linux主机的用户.这里我们做的例子就是:新建一个liunx用户,并为该l ... 
- 【Java并发编程】8、各种锁的概念
			持续更新中... 共享锁(S锁):如果事务T对数据A加上共享锁后,则其他事务只能对A再加共享锁,不能加排他锁,直到已释放所有共享锁.获准共享锁的事务只能读数据,不能修改数据. 排他锁(X锁):如果事务 ... 
- Arrays工具类的aslist()方法的使用
			数组转换成集合: 数组转换成集合不能增加或减少元素,但是可以用集合思想操作数组,也就是说可以使用其他集合中的办法 String[] arr = {"a", "b" ... 
- HDU3440(差分约束)
			House Man Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total S ... 
