前言:以前的项目中文件上传下载会写大量代码来实现,但是在Spring Boot中,简化了大量代码,上传只需要2行代码即可
package com.demo.controller;
import com.demo.model.FileInfo;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
/**
* @Auther: MQS
* @Date: 18/09/11 11:50
* @Description:
*/
@RestController
@RequestMapping("/file")
public class FileController {
//文件上传路径
private String folder = "F:/";
/**
* 文件上传
* @param file
* @return
* @throws Exception
*/
@PostMapping
public FileInfo upload(MultipartFile file) throws Exception {
System.out.println(file.getName());
System.out.println(file.getOriginalFilename());
System.out.println(file.getSize());
File localFile = new File(folder, System.currentTimeMillis()+".txt");
file.transferTo(localFile);
return new FileInfo(localFile.getAbsolutePath());
}
/**
* 文件下载
* @param name
* @param request
* @param response
* @throws Exception
*/
@GetMapping("/{name}")
public void downLoad(@PathVariable String name, HttpServletRequest request, HttpServletResponse response) throws Exception{
try (InputStream inputStream = new FileInputStream(new File(folder, name+".txt"));
OutputStream outputStream = response.getOutputStream();){
response.setContentType("application/x-download");
//addHeader 可以修改文件下载时的名称
// response.addHeader("Content-Disposition", "attachment;filename=test.txt");
IOUtils.copy(inputStream, outputStream);
outputStream.flush();
}
}
}
文中示例为上传txt文件,上传其他类型文件后缀名可以根据需要自行获取,修改
下载代码里的 inputStream 和 outputStream 写在try 后面的括号里 是java7 之后的新特性,可以自动关闭流