springMVC文件的上传与下载

文件的上传和下载

  1. 使用request对象,和servlet的文件上传一样
  2. commons-fileupload.jar进行文件上传 springMVC提供了 multipartResovler 接口来处理 文件上传
  • CommonsMultipartResolver 是 multipartResovler 实现类

  • CommonsMultipartResovler上传文件的功能实现就是通过Apache提供的FileUpload来实现

  • StandardServletMultipartResolver 是 multipartResovler 实现类文件上传功能是使用了 request.getPart()来实现

配置文件相关配置

<!-- 文件上传解析器配置  id只能是multipartResolver -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
	<!-- 设置字符编码格式为utf8 -->
	<property name="defaultEncoding" value="utf8"></property>
	<!-- 设置上传文件的最大的字节数 默认为-1不限制大小 -->
	<property name="maxUploadSize" value="5000000"></property>
	<!-- 设置文件的缓存大小  默认值为10kb 超出该大小将会把内存中的内容输出到文件中 -->
	<property name="maxInMemorySize" value="10240"></property>
	<!-- 还有其它属性可设置,例如临时文件的位置、多文件时,每个文件的大小限制等等 -->	
</bean>

web.xml相关配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="4.0" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd">

<!-- The front controller of this Spring Web application, responsible for handling all application requests -->
<servlet>
	<servlet-name>springDispatcherServlet</servlet-name>
	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	<init-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:配置文件名称</param-value>
	</init-param>
	<load-on-startup>1</load-on-startup>
</servlet>

<!-- Map all requests to the DispatcherServlet for handling -->
<servlet-mapping>
	<servlet-name>springDispatcherServlet</servlet-name>
	<url-pattern>/</url-pattern>
</servlet-mapping>

</web-app>

具体代码实现

上传单个文件

MultipartFile就是接收到的文件
@RequestMapping(value = 访问路径,method = RequestMethod.POST)
public String upload(MultipartFile file) throws IllegalStateException, IOException {
	System.out.println(file);
	//获取文件名
	String fileName = file.getOriginalFilename();
	System.out.println("fileName = " + fileName);
	//获取文件类型
	String type = file.getContentType();
	System.out.println("type = " + type);
	//获取文件大小
	long size = file.getSize();
	System.out.println("size = " + size);
	
	String destPath = "文件路径" + fileName;
	File destFile = new File(destPath);
	//将文件存储到指定的文件或者路径下
	file.transferTo(destFile);
	System.out.println("上传完成");
	return "index";
}

上传多个文件
法1:

@RequestMapping(value = 访问路径,method = RequestMethod.POST)
//将input的name属性值为file的文件都存放在files数组中
public String uploads(@RequestParam(name = "file",required = false) MultipartFile[] files) throws IllegalStateException, IOException {
	//当前端没有提交文件时,file对象的size就是0
	for(MultipartFile file : files) {
		System.out.println(file);
		String fileName = file.getOriginalFilename();
		//如果上传的文件的名称在该路径下已经存在,新上传的文件会将原来的覆盖掉,为了防止覆盖为文件名上拼接上时间戳
		//split的参数是正则表达式, .在正则中代表任意字符,此处需要将.转移成 点本身 \\.就代表.这个字符
		String[] names = fileName.split("\\.");
		System.out.println(Arrays.toString(names));
		/*
		 * 通常情况下,文件名是由名称.后缀名组成的话,names={文件名,后缀名}。
		 * 但是有的文件 没有后缀名 切割完就是names={文件名};此时我们的names[1] 就会数组越界
		 */
		if(names.length == 2) {
			//有后缀
			fileName = names[0] + "_" + System.currentTimeMillis() + "." + names[1];
		}else if(names.length == 1) {
			fileName = names[0] + "_" + System.currentTimeMillis();
		}
		System.out.println(fileName);
		String destPath = "文件路径" + fileName;
		File destFile = new File(destPath);
		//将文件存储到指定的文件或者路径下
		file.transferTo(destFile);
		System.out.println("上传完成");
	}
	return "index";
}

法2:

@RequestMapping(value = "访问路径",method = RequestMethod.POST)
public String uploads_2(@RequestParam(name="file",required = false)MultipartFile[] files) {
	System.out.println(files);
	for (MultipartFile file : files) {
		System.out.println(file);
	}
	return "index";
}

下载文件 ResponseEntity对象

@RequestMapping("访问路径")
public ResponseEntity<byte[]> download(@RequestParam String fileName) throws IOException{
	System.out.println(fileName);
	String filePath = "文件路径" + fileName;
	File file = new File(filePath);
	if(file.exists()) {
		//将文件转换为字节流
		byte[] content = FileUtils.readFileToByteArray(file);
		//设置响应头
		HttpHeaders headers = new HttpHeaders();
		//解决文件名下载时的中文乱码
       //fileName = new String(fileName.getBytes(),"utf8");
		fileName=new String(file.getName().getBytes("utf-8"),"iso-8859-1");
		System.out.println(fileName);
		//设置下载时的文件名
		headers.setContentDispositionFormData("attachment", fileName);
		//设置文件类型  流文件类型
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		//创建entity对象
		//响应给前端的内容  参数1.响应的正文(内容)  2.响应头  3.响应的状态码
		ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(content, headers, HttpStatus.OK);
		return entity;
	}
	return null;
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值