SpringBoot学习记录(八):文件的上传(含多文件上传)和下载

前言

在项目的开发过程中,或多或少都会涉及到文件的上传和下载,比如说(Excel、word)等等,这篇文章主要记录在SpringBoot项目中,如何实现单个文件的上传和下载,以及多文件的上传。

PS:本文中的前端展示界面使用thymeleaf模板。不会的可以参考右边的文章?SpringBoot整合Thymeleaf模板

Thymeleaf模板

<body>
	<h3>单个文件上传</h3>
	<form action="/file/upload" enctype="multipart/form-data" method="post">
		文件选择:<input type="file" name="file">
				 <input type="submit" value="上传">
	</form>
	<h3>多个文件上传</h3>
	<form action="/file/uploadAll" enctype="multipart/form-data" method="post">
		文件选择1:<input type="file" name="fileName"><br>
		文件选择2:<input type="file" name="fileName"><br>
		文件选择3:<input type="file" name="fileName">
				  <input type="submit" value="上传">
	</form>
	
	<a href="/file/download">下载</a>
</body>

Controller

@Controller
@RequestMapping("/file/")
public class FileController {
	
	/**
	 * 	文件下载
	 */
	@RequestMapping("download")
	public void download(HttpServletResponse response) {
		//被下载的文件路径
		String filePath = "D:/upload/";
		//被下载的文件名
		String fileName = "123.txt";
		//文件对象
		File file = new File(filePath+fileName);
		//设置类型为强制下载
		response.setContentType("application/force-download");
		//设置下载后的文件名
		response.setHeader("Content-Disposition", "attachment;fileName="+fileName);
		//设置编码格式
		response.setCharacterEncoding("UTF-8");
		//文件下载
		try {
			//缓冲区读取数据
			BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
			//输出流
			OutputStream os  = response.getOutputStream();
			//创建字节数组
			byte[] buff = new byte[(int)file.length()];
			//读取
			int i = 0;
			while((i=bis.read(buff)) > 0) {
				os.write(buff);
			}
			os.close();
			bis.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} 
		
	}
	
	
	/**
	  *  多个文件上传
	 *    	1、使用@RequestParam("fileName")注解方式获取文件集合files 
	 * 			public String uploadAll(@RequestParam("fileName") List<MultipartFile> files) {}
	 *		2、使用HttpServletRequest获取文件集合files
	 *			public String uploadAll(HttpServletRequest request) {
	 *			List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("fileName");
	 */
	@RequestMapping("uploadAll")
	@ResponseBody
	public String uploadAll(HttpServletRequest request) {
		List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("fileName");
		//上传文件路径
		String filePath = "D:/upload/";
		MultipartFile file = null;
		//上传成功个数
		int num = 0;
		for (int i = 0; i < files.size(); i++) {
			//获取第i个文件
			file = files.get(i);
			//获取文件名
			String fileName = file.getOriginalFilename();
			//文件的绝对路径
			fileName = filePath + new SimpleDateFormat("YYYYMMddHHmmss").format(new Date()) + fileName;
			//获取当前文件对象
			File dest = new File(fileName);
			//判断父目录是否存在,不存在就创建
			if(!dest.getParentFile().exists()) {
				dest.getParentFile().mkdir();
			}
			try {
				file.transferTo(dest);
				num++;
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		return "文件上传 - 共"+files.size()+"个文件,成功"+num+"个,失败"+(files.size()-num)+"个";
		
	}

	/**
	 * 	单个文件上传
	 */
	@RequestMapping("upload")
	@ResponseBody
	public String upload(@RequestParam("file") MultipartFile file) {
		//获取文件名
		String fileName = file.getOriginalFilename();
		//上传的文件路径
		String filePath = "D:/upload/";
		//上传文件的绝对路径
		fileName = filePath + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + fileName;
		//获取文件对象
		File dest = new File(fileName);
		//判断父目录是否存在,不存在则创建
		if(!dest.getParentFile().exists()){
			dest.getParentFile().mkdir();
		}
		//上传文件
		try {
			file.transferTo(dest);
			return "文件上传成功!";
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return "文件上传失败!";
	}
	
	
}

Exception

上传时遇到报错org.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededException

原因:文件上传过大,SpringBoot的默认上传文件的大小是2m 如果你上传的文件超过了2m就会出现这样的错误。
解决方案:设置文件的上传大小。?

关于上传下载的一些配置

1、配置文件方式配置

spring:
  servlet:
    multipart:
      enabled: true #是否支持多个文件上传(默认true)
      max-file-size: 1MB  #设置上传的单个文件的大小上限
      max-request-size: 10MB #设置总上传的大小上限

2、自定义配置类

ps:自定义配置类已过时,建议使用配置文件方式进行配置。

/**
 * 	文件上传下载的自定义配置类
 */
@Configuration
public class MultipartFileProperties {
	@Bean
	public	MultipartConfigElement multipartConfigElement() {
		MultipartConfigFactory factory = new MultipartConfigFactory();
		
		//设置单个文件大小
		factory.setMaxFileSize("1024KB");
		//设置总上传的大小
		factory.setMaxRequestSize("1024KB");
		
		return factory.createMultipartConfig();
	}
}

本文为初学者学习记录,有什么讲的不对的地方欢迎指出。谢谢!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值