单文件上传
@RestController
@RequestMapping("/upload")
public class upload {
Logger log = LoggerFactory.getLogger(upload.class);
@PostMapping("/file")
public String upload(@RequestPart("file") MultipartFile multipartFile) {
log.info(multipartFile.getName());// 获取上传文件前端定义的名称
log.info(multipartFile.getContentType()); // 文件类型
log.info(multipartFile.getOriginalFilename());// 文件原始名称
long fileSize = multipartFile.getSize();
log.info(fileSize+""); // 文件大小
log.info(multipartFile.isEmpty()+""); // 文件是否为空
// 要上传的文件目录
String path = null;
// 获取文件的输入流 InputStream inputStream = multipartFile.getInputStream();
try {
if(multipartFile.isEmpty()) {
return "文件不能为空";
}
// /D:/biancheng_files/Maven/spring_boot_01/target/classes/
// 判断下文件目录是否存在,不存在的话 创建
File isExistFile = new File(ResourceUtils.getURL("classpath:").getPath()+"static/image");
if(!isExistFile.exists()) {
isExistFile.mkdirs();
}
path = ResourceUtils.getURL("classpath:").getPath()+"static/image/"+multipartFile.getOriginalFilename();
// 保存到哪里
multipartFile.transferTo(new File(path));
} catch (IOException e) {
e.printStackTrace();
}
return "http://localhost:9000/image/"+multipartFile.getOriginalFilename();
}
}
2021年12月10日 - 补充:
file.getSize() 拿到的是上传文件的大小,单位是字节(Byte)。
1024Byte = 1kb
1024kb = 1MB
1MB转化为字节: 1MB = 1*1024*1024 = 1048576字节
所有与上传有关的配置:
默认文件大小为:1MB,
补充:
也可以使用 FileOutputStream输出流 来保存上传的资源
@RestController
@RequestMapping("/upload")
public class upload {
Logger log = LoggerFactory.getLogger(upload.class);
@PostMapping("/file")
public String upload(@RequestPart("file") MultipartFile multipartFile) {
// 要上传的文件目录
String path = null;
try {
if(multipartFile.isEmpty()) {
return "文件不能为空";
}
// 判断下文件目录是否存在,不存在的话 创建
File isExistFile = new File(ResourceUtils.getURL("classpath:").getPath()+"static/image");
if(!isExistFile.exists()) {
isExistFile.mkdirs();
}
path = ResourceUtils.getURL("classpath:").getPath()+"static/image/"+multipartFile.getOriginalFilename();
// 创建输出流
FileOutputStream fos = new FileOutputStream(new File(path), true);
// 获取 上传资源的字节数组,写到path中
fos.write(multipartFile.getBytes());
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
return "http://localhost:9000/image/"+multipartFile.getOriginalFilename();
}
}