文件上传时对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")//MultipartFile参数用于接受文件,参数名为前端提交的文件名,
private R upload(MultipartFile file) {
// 当前的file是一个临时文件,当本次请求结束后该file就会被删除,所以需要进行转存,
log.info(file.toString());
//获取上传时的文件名称,并通过文件名获取文件格式
String originalFilename = file.getOriginalFilename();
assert originalFilename != null;
String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
//使用UUID重新随机生成文件名,防止文件民称重复遇文件覆盖
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();
}
}
}



