多文件上传
<body>
<form id="form" action="/uploads" method="post" enctype="multipart/form-data">
<input type="file" name="files" multiple/>
<input type="input" name="remark"/>
<input type="submit" value="submit"/>
</form>
</body>
// 创建目录
SimpleDateFormat sft = new SimpleDateFormat("/yyyy/MM/dd/");
@PostMapping("/uploadsFd")
// 接收formData提交
public String uploadsFd(HttpServletRequest req,
HttpServletResponse rsq,
@RequestParam(required = false, value = "files") MultipartFile[] files,
@RequestParam(required = false, value = "remark") String remark) {
System.out.println("remark = " + remark);
realPath = req.getServletContext().getRealPath("/img") + format;
return upLoadedUrls(req, files, realPath);
}
private String upLoadedUrls(HttpServletRequest req, @RequestParam(required = false, value = "files") MultipartFile[] files, String realPath) {
String reUrl = "";
List<String> urls = new ArrayList<>();
File folder = new File(realPath);
if (!folder.exists()) {
folder.mkdirs();
}
for (MultipartFile file : files) {
String oldName = file.getOriginalFilename();
String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
try {
file.transferTo(new File(folder, newName));
String url = req.getScheme() + "://" + req.getServerName()
+ ":" + req.getServerPort() + "/img" + format + newName;
System.out.println("url = " + url);
urls.add(url);
} catch (IOException e) {
e.printStackTrace();
}
}
return String.join(",",urls);
}
单文件上传
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit" value="submit"/>
</form>
@PostMapping("/upload")
public String upload(MultipartFile file, HttpServletRequest req) {
String format = sft.format(new Date());
// 创建真实路径
String realPath = req.getServletContext().getRealPath("/img") + format;
File folder = new File(realPath);
// 创建目录s
if (!folder.exists()) {
folder.mkdirs();
}
String oldName = file.getOriginalFilename();
// 创建文件名
String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
try {
// 保存文件
file.transferTo(new File(folder, newName));
String url = req.getScheme() + "://" + req.getServerName()
+ ":" + req.getServerPort() + "/img" + format + newName;
return url;
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
网友评论