java文件上传
【java文件上传】多文件上传
// 创建目录
SimpleDateFormat sft = new SimpleDateFormat("/yyyy/MM/dd/");
@PostMapping("/uploadsFd")
//接收formData提交
public String uploadsFd(HttpServletRequest req,
HttpServletResponse rsq,
@RequestParam(required = false, value = "https://www.it610.com/article/files") MultipartFile[] files,
@RequestParam(required = false, value = "https://www.it610.com/article/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 = "https://www.it610.com/article/files") MultipartFile[] files, String realPath) {
String reUrl = "";
List 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);
}
单文件上传
@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 "";
}
推荐阅读
- JAVA(抽象类与接口的区别&重载与重写&内存泄漏)
- 事件代理
- Java|Java OpenCV图像处理之SIFT角点检测详解
- django-前后端交互
- 如何在Mac中的文件选择框中打开系统隐藏文件夹
- java中如何实现重建二叉树
- 使用composer自动加载类文件
- 数组常用方法一
- 【Hadoop踩雷】Mac下安装Hadoop3以及Java版本问题
- Java|Java基础——数组