学习记录:
controller:
@PostMapping("/upload")
public String upload(@RequestParam("username" ) String username,
@RequestParam("email") String email,
@RequestPart("headerImg") MultipartFile headerImg,
@RequestPart("photos") MultipartFile [] photos) throws IOException {
log.info("上传的信息时; usernmae={},email={},headerImg={},phots={}",username,email,headerImg.getSize(),photos.length);
if (!headerImg.isEmpty()){
//保存到文件服务器 ,oss服务器
// 第一种:
// headerImg.transferTo(upload);
// 第二种:
InputStream inputStream = headerImg.getInputStream();
File upload= new File("D:\\upload\\" + System.currentTimeMillis()+new Random(1).nextInt(1000)+headerImg.getOriginalFilename().substring(headerImg.getOriginalFilename().lastIndexOf(".")));
OutputStream outputStream=new FileOutputStream(upload);
byte []datas=new byte[1024];
int len;
while ((len=inputStream.read(datas))!=-1){
outputStream.write(datas,0,len);
}
inputStream.close();
outputStream.close();
}
if (photos.length>0){
for (MultipartFile photo : photos) {
if (!photo.isEmpty()){
String originalFilename = photo.getOriginalFilename();
String imgName=System.currentTimeMillis()+new Random(1).nextInt(1000)+originalFilename.substring(originalFilename.lastIndexOf("."));
log.info("生活照文件名:{}",imgName);
photo.transferTo(new File("D:\\upload\\" + imgName));
}
}
}
return "main";
}
}
html: