java多文件上传主要代码

上传文件方法代码

R为自定义的返回数据包装对象,不是重要部分

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
@RequestMapping("/uploadImg")
public R uploadImg(@RequestParam("img") MultipartFile[] files, HttpServletRequest request) {
Map<String, Object> result = new HashMap<>();
if(files.length<=0){
return R.error("请选择图片");
}
String uploadPath = System.getProperty("user.dir") + "/files/";
try {
List<String> urls=new ArrayList<>();
for(MultipartFile file:files){
if (file.isEmpty()) {
continue;
}
String fileName = file.getOriginalFilename();
fileName = FileUtil.renameToUUID(fileName);
try {
FileUtil.uploadFile(file.getBytes(), uploadPath, fileName);
} catch (Exception e) {
e.printStackTrace();
}
urls.add("/files/" + fileName);
}
result.put("urls", urls);
} catch (Exception e) {
return R.error("上传图片失败!");
}

if (result != null && result.size() > 0) {
return R.ok(result);
} else {
return R.error("上传图片失败!");
}
}

类FileUtil代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.app.common.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.util.UUID;

public class FileUtil {

public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
File targetFile = new File(filePath);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
FileOutputStream out = new FileOutputStream(filePath + fileName);
out.write(file);
out.flush();
out.close();
}

public static boolean deleteFile(String fileName) {
File file = new File(fileName);
// 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
if (file.exists() && file.isFile()) {
if (file.delete()) {
return true;
} else {
return false;
}
} else {
return false;
}
}

public static String renameToUUID(String fileName) {
return UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
}
}