Java后端接收多个文件
java后端接收多个文件,因为是多个文件,所以在接收的时候可以使用
1、List
2、MultipartFile[]
这两种其实都能接收到多个文件列表,接收到之后再遍历,获取文件,对文件进行存储即可。
保存文件
/**
* 接收传递的文件数组
* @param multipartFiles multipartFiles
* @return result
*/
public List<String> receiveFileToDir(List<MultipartFile> multipartFiles) {
// 输出的文件流保存到本地文件
// uploadDir 是设置好的文件保存地址,可自行设置
String path = uploadDir;
// 判断文件保存目录是否存在,不存在则创建相关目录
File tempFile = new File(path);
if (!tempFile.exists()) {
tempFile.mkdirs();
}
List<String> fileNameList = new ArrayList<>();
for (MultipartFile file : multipartFiles){
OutputStream os = null;
InputStream inputStream = null;
String originalFilename = file.getOriginalFilename();
String[] split = originalFilename.split("\\.");
String fileName = codeUtilBuil() + "." + split[1];
try {
inputStream = file.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
// File.separato 系统默认分隔符,相当于 /
try {
os = new FileOutputStream(tempFile.getPath()+ "/" + File.separator + fileName);
// 开始读取
byte[] bs = new byte[1024];
// 读取数据
int length;
while ((length = inputStream.read(bs)) != -1) {
os.write(bs, 0, length);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭所有链接
try {
os.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
fileNameList.add(path + "/" +fileName);
}
return fileNameList;
}
重命名文件名:
/**
* 上传文件名序号
* @return
*/
public String codeUtilBuil(){
StringBuffer sb = new StringBuffer();
Random random = new Random();
for (int i = 0; i < 12; i++) {
int y = random.nextInt(62);
if (y <= 9) {
sb.append(y);
} else {
if (y <= 35) {
y += 55;
} else {
y += 61;
}
sb.append((char) y);
}
}
return sb.toString();
}