1.单文件上传到服务器
index.html
Title
fileController
@RestController
public class fileuploadController {
SimpleDateFormat sdf=new SimpleDateFormat("/yyyy/MM/dd/");
@RequestMapping("/upload")
public String upliad(MultipartFile file, HttpServletRequest req){
//获取临时目录
String realpath=req.getServletContext().getRealPath("/");
//最终路径
String format = sdf.format(new Date());
String path=realpath+ format;
File folder=new File(path);
if (!folder.exists()){
folder.mkdirs();
}
String oldName = file.getOriginalFilename();
String newName= UUID.randomUUID().toString()+oldName.substring(oldName.lastIndexOf("."));
try {
file.transferTo(new File(path+newName));
String newName1 =req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+req.getContextPath()+format+ newName;
return newName1;
// return path;
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
}
返回结果
打开链接就可以看见上传的文件
2.单文件上传到本地
@RequestMapping("/upload")
public String upload2(@RequestBody MultipartFile file, HttpServletRequest req) throws IOException {//MultipartFile 接收前端传过来的文件
String format = sdf.format(new Date());
String path="D:/img"+format;
File folder=new File(path);
if (!folder.exists()){
folder.mkdirs();
}
String oldName = file.getOriginalFilename();
String newName= UUID.randomUUID().toString()+oldName.substring(oldName.lastIndexOf("."));
file.transferTo(new File(path+newName));
return path+ newName;
}



