82 lines
2.3 KiB
Java
82 lines
2.3 KiB
Java
package com.szxgl.pars2021.utils;
|
|
|
|
import org.apache.commons.io.IOUtils;
|
|
import org.springframework.web.multipart.MultipartFile;
|
|
|
|
import java.io.File;
|
|
import java.io.FileOutputStream;
|
|
import java.io.IOException;
|
|
import java.io.InputStream;
|
|
import java.text.SimpleDateFormat;
|
|
import java.util.Date;
|
|
import java.util.UUID;
|
|
|
|
public class FileUpLoad {
|
|
|
|
public static String upload(String parentPath, MultipartFile fileImage){
|
|
|
|
//如果没有上传文件就为null
|
|
if (fileImage == null) {
|
|
return null;
|
|
}
|
|
InputStream is = null;
|
|
String fileName = null;
|
|
String newPath = null;
|
|
FileOutputStream os = null;
|
|
String name = null;
|
|
|
|
try {
|
|
//获取输入流
|
|
is = fileImage.getInputStream();
|
|
|
|
//获取文件名
|
|
fileName = fileImage.getOriginalFilename();
|
|
//文件名处理,加上一串随机数
|
|
fileName = UUID.randomUUID().toString().replaceAll("-","") + fileName;
|
|
|
|
//判断文件夹是否创建
|
|
File file = new File(parentPath);
|
|
if(!file.exists()){
|
|
file.mkdirs();
|
|
}
|
|
|
|
//根据时间创建文件夹名称
|
|
newPath = new SimpleDateFormat("yyyyMMdd").format(new Date());
|
|
newPath = parentPath + "/" + newPath;
|
|
File file2 = new File(newPath);
|
|
if(!file2.exists()){
|
|
file2.mkdirs();
|
|
}
|
|
|
|
//获取输出流
|
|
os = new FileOutputStream(new File(newPath, fileName));
|
|
//进行复制
|
|
IOUtils.copy(is,os);
|
|
} catch (IOException e) {
|
|
e.printStackTrace();
|
|
}finally {
|
|
try {
|
|
if (os != null) {
|
|
os.close();
|
|
}
|
|
if (is != null) {
|
|
is.close();
|
|
}
|
|
} catch (IOException e) {
|
|
e.printStackTrace();
|
|
}
|
|
}
|
|
|
|
name = "/" + newPath.substring(newPath.lastIndexOf("\\")+1) + "/" + fileName;
|
|
|
|
return name;
|
|
}
|
|
|
|
public static void main(String[] args) {
|
|
String url = "D:\\file/2021111022379fe88b5f44f797271c0dc39d3019WeChat_20211110092809.mp4";
|
|
url = url.substring(url.lastIndexOf("\\")+1);
|
|
System.out.println(url);
|
|
|
|
}
|
|
}
|