基于Spring MVC的文件上传和下载功能的实现
2024-08-27 16:58:54
配置文件中配置扫描包,以便创建各个类的bean对象
<context:component-scan base-package="com.neuedu.spring_mvc"></context:component-scan>
一、文件的上传
Spring MVC 上下文中默认没有为文件上传提供了直接的支持,因此默认情况下不能处理文件的上传工作
如果想使用 Spring 的文件上传功能,需现在上下文中配置 CommonsMultipartResovler:
1、加入jar包:
commons-fileupload-1.3.1.jar
commons-io-2.4.jar
Maven项目通过在pom.xml文件中配置jar包依赖
<dependency>
<groupId>commons-fileupload</groupId>
3 <artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
10 </dependency>
2、在SpringMVC配置文件中配置CommonsMultipartResovler
<!-- 配置CommonsMultipartResolver,必须配置id值为multipartResolver -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property>
<!-- 以字节为单位 -->
<property name="maxUploadSize" value="1024000"></property>
</bean>
3、表单的设置
POST请求,file类型,enctype="multipart/form-data"
<form action="${pageContext.request.contextPath}/upload" method="post" enctype="multipart/form-data">
文件:<input type="file" name="file"/>
描述:<input type="text" name="desc"/>
<input type="submit" value="上传"/>
</form>
4、上传的实现
@Controller
public class TestController {
@RequestMapping(value="/upload",method=RequestMethod.POST)
public String upload(@RequestParam(value="desc") String desc,
@RequestParam(value="file") CommonsMultipartFile file,HttpServletRequest request) throws IOException{
ServletContext context = request.getSession().getServletContext();
//获取真实路径,使用tomcat插件,默认路径为webapp下
String realPath = context.getRealPath("/upload"); //判断upload文件夹是否存在
File file1=new File(realPath);
if(!file1.exists()){
file1.mkdir();
} //文件名添加uuid,防止重复
String uuid=UUID.randomUUID().toString().replace("-", "");
String fileName=uuid+"_"+file.getOriginalFilename();
//获取输入流
InputStream in=file.getInputStream();
//获取输出流,指定输出路径及文件名
FileOutputStream out=new FileOutputStream(new File(realPath+"\\"+fileName));
IOUtils.copy(in, out);
out.close();
in.close();
return "success";
}
}
二、文件的下载
用ResponseEntity<byte[]> 返回值完成文件下载
@Controller
public class TestController {
@RequestMapping(value="/download")
public ResponseEntity<byte[]> download(HttpSession session) throws IOException{
byte[] body=null;
ServletContext context = session.getServletContext();
String fileName="d5b9b61dc7154f5c9df4c844348ef6df_fennu.jpg"; //获取文件路径
String filePath = context.getRealPath("/upload/"+fileName);
//读取文件内容
InputStream in=new FileInputStream(new File(filePath));
//创建文件字节数组,数组长度为文件的总大小
body=new byte[in.available()];
//将文件内容保存到字节数组中
in.read(body); //创建响应头信息的MultiValueMap
MultiValueMap<String, String> headers=new HttpHeaders();
//设置文件名重新编码,以gbk格式读取再编码为iso8859-1
fileName=new String(fileName.getBytes("gbk"), "iso8859-1");
//设置响应信息
headers.add("Content-Disposition", "attachment;filename="+fileName); HttpStatus statusCode=HttpStatus.OK;
ResponseEntity<byte[]> responseEntity=new ResponseEntity<byte[]>(body, headers, statusCode);
in.close();
return responseEntity;
}
}
最新文章
- ASP.NET MVC5+EF6+EasyUI 后台管理系统(18)-权限管理系统-表数据
- Oracle转换时间出现的问题:ORA-01810: format code appears twice
- Struts2常量的具体用法实例
- Windows Azure Virtual Network (6) 设置Azure Virtual Machine固定公网IP (Virtual IP Address, VIP) (1)
- PHP 缓存扩展opcache
- python两个文件的对比
- Network - Tcpdump
- XtraScheduler 日程控件显示自定义标题
- (window)Android Studio安装以及Fetching android sdk component information超时的解决方案
- OpenGL学习——基本概念和坐标变换
- codeforces 395B2 	 iwiwi
- VoltDB公布4.0版本号,大步提高内存实时分析速度,进军操作数据库市场
- MySQL存储过程详解 mysql 存储过程
- 【POJ2417】baby step giant step
- Unique Binary Search Trees 解答
- javascript之函数节流
- jQuery判断滚动条滚到页面底部脚本
- visual studio的包含目录配置问题
- Oarcle 入门之注释与关键字
- 网页三剑客:HTML+CSS+JavaScript 之CSS概述