SpringBoot的文件上传与下载
前端代码
文件上传时对form表单有如下要求
- method:="post"采用post方式提交数据
- enctype="multipart/form-data"采用multipart格式上传文件
- type="file"使用input的file控件上传
也可以使用一些前端组件库提供的相对应的上传组件,例如ElementUi中提供的upload组件库
后端代码
服务端上传组件会使用apache提供的俩个组件,
- Commons- fileuoload
- commons - id
但是在SpringBoot中Spring框架在spring-web包中对文件上传进行了封装,大大简化了服务端代码,我们只需要在ControllerE的方法中声明 一个MultipartFile类型的参数即可接收上传的文件
具体代码
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
@Value("${reggie.path}")
private String basePath;
@PostMapping("/upload")
private R<String> upload(MultipartFile file) {
log.info(file.toString());
String originalFilename = file.getOriginalFilename();
assert originalFilename != null;
String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
String fileName = UUID.randomUUID().toString() + suffix;
File path = new File(basePath);
if (!path.exists()) {
path.mkdirs();
}
try {
System.out.println(basePath+fileName);
file.transferTo(new File(basePath + fileName));
} catch (IOException e) {
e.printStackTrace();
}
return R.success(fileName);
}
@GetMapping("/download")
public void download(String name, HttpServletResponse response) {
try {
FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));
ServletOutputStream outputStream = response.getOutputStream();
response.setContentType("image/jpeg");
int len = 0;
byte[] bytes = new byte[1024];
while ( (len = fileInputStream.read(bytes)) != -1){
outputStream.write(bytes,0,len);
outputStream.flush();
}
outputStream.close();
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|