/**
* 文件上传总结:
* 1.标注注解 @RequestPart(name = "file1") MultipartFile multipartFile1
* (1)不指定 name 时,上传文件的参数名称默认为 multipartFile1 来找到对应文件
*(2)指定 name 时,上传文件的参数名称为 file1 来找到对应文件
*(3)上传文件如果参数名称错误,将会报错
* <p>
* 2.不标注注解 @RequestPart(name = "file1")
*(1)上传文件的参数名称默认为 multipartFile1 来找到对应文件
*(2)上传文件如果参数名称错误,不会报错,但是 multipartFile1会为null
* <p>
* 3.关于 MultipartFile 属性
* (1)multipartFile1.getName():上传文件的参数名称
* (2)multipartFile1.getOriginalFilename():文件完整名称(不包含路径)
*/
@RequestMapping("/fileUpload")
public String fileUpload(@RequestPart(name = "file1") MultipartFile multipartFile1,
HttpServletRequest request
) throws Exception {
if (multipartFile1.isEmpty()) {
return "图片multipartFile1为空";
}
//文件完整名称(不包含路径)
String originFileName = multipartFile1.getOriginalFilename();
//1.创建文件夹
String dirPath = "upload";
//获取类路径的绝对路径
String classPath = UserController.class.getClassLoader().getResource("/").getPath();
File dir = new File(classPath + "\\" + dirPath);
if (!dir.exists()) {
dir.mkdir();
}
String saveFilePath = classPath + dirPath + "\\" + System.currentTimeMillis() + "_" + originFileName;
//2.保存文件到本地
//方法1:
//FileOutputStream os = new FileOutputStream(saveFilePath);
//os.write(multipartFile1.getBytes());
//os.flush();
//os.close();
//方法2:
// InputStream is = multipartFile1.getInputStream();
// FileOutputStream os = new FileOutputStream(saveFilePath);
// byte[] bytes = new byte[1024];
// int len = -1;
// while ((len = is.read(bytes)) != -1) {
// System.out.println(len);
// os.write(bytes, 0, len);
// }
// os.flush();
// is.close();
// os.close();
//方法3
multipartFile1.transferTo(new File(saveFilePath));
return "成功";
}