七、spring boot 2.x 文件上传下载

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/LDY1016/article/details/83444257

1、在application.properties中添加文件上传的配置信息

  在1.x版本中application.properties中的配置信息如下

#文件上传配置
spring.http.multipart.maxFileSize=50Mb
spring.http.multipart.maxRequestSize=50Mb

  在2.x版本中application.properties的配置如下,我们这里使用2.x的配置方式

#文件上传配置
spring.servlet.multipart.maxFileSize=50Mb
spring.servlet.multipart.maxRequestSize=50Mb

  从1.x到2.x,配置有点小的变动,spring.http.multipart变更为spring.servlet.multipart,大家在使用的时候注意一下

2、在application.properties中自定义文件上传路径,后面我们通过@Value注解方式获取

#自定义配置-文件上传路径 上传到当前项目的files文件夹下
self.file.uploadPath=${user.dir}/files

3、编写文件上传下载接口:FileController.java

package com.ldy.bootv2.demo.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@Api(tags = "文件上传下载接口-API")
@RequestMapping(value = "/file")
public class FileController {

	private static Logger logger = LoggerFactory.getLogger(FileController.class);

	/**
	 * 文件存放路径,配置在application.properties文件中
	 */
	@Value(value = "${self.file.uploadPath}")
	private String uploadPath;

	@PostMapping("/upload")
	@ApiOperation("文件上传接口")
	public String upload(@ApiParam(value = "文件", required = false) final MultipartFile file) {
		if (null == file) {
			logger.error("文件上传失败,文件不能为空");
			return "error";
		}

		File dir = new File(uploadPath);
		if (!dir.exists()) {
			dir.mkdirs();
		}
	
		File saveFile = new File(uploadPath, file.getOriginalFilename());
		
		try {
			// 保存到指定路径
			file.transferTo(saveFile);
			// TODO 将上传的文件信息保存到数据库
		} catch (Exception e) {
			logger.error("文件上传失败,原因:", e);
			return "error";
		}

		logger.info("文件上传成功,fileName = " + file.getOriginalFilename());
		return "success";
	}

	
	
	@PostMapping("/download")
	@ApiOperation("文件下载接口")
	@ApiImplicitParam(name = "fileName", value = "文件名称", required = true, dataType = "String")
	public String download(HttpServletResponse response,@RequestParam String fileName) {
		if (StringUtils.isEmpty(fileName)) {
			logger.error("文件下载失败,原因:文件名不能为空");
			return "error";
		}
		try {
			File file = new File(uploadPath + "/" + fileName);
			response.setCharacterEncoding("utf-8");
			response.setContentType("multipart/form-data");
			fileName = new String(fileName.getBytes(), "ISO-8859-1");
			response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
			InputStream inputStream = new FileInputStream(file);
			OutputStream os = response.getOutputStream();
			byte[] b = new byte[1024];
			int length;
			while ((length = inputStream.read(b)) > 0) {
				os.write(b, 0, length);
			}
			inputStream.close();
		} catch (Exception e) {
			logger.error("文件下载失败,原因:", e);
			return "error";
		}

		logger.info("文件下载成功,fileName = " + fileName);
		return "success";
	}

}

4、启动项目,通过swagger页面测试接口,swagger的集成请查看:https://blog.csdn.net/LDY1016/article/details/83415640

(1)文件上传测试

选择文件后点击“Execute”按钮

(2)文件下载测试

输入文件名称后点击“Execute”按钮

源码下载地址:https://pan.baidu.com/s/1Z771VDiuabDBJJV445xLeA#list/path=%2Fspring%20boot%202.x%20%E4%BB%A3%E7%A0%81

猜你喜欢

转载自blog.csdn.net/LDY1016/article/details/83444257
今日推荐