@Service
@Slf4j
public class FileUploadService {
@Resource
private Environment environment;
//获取文件存储路径
@Value("${upload.root.path}")
private String upfilePath;
//获取图片类型
@Value("${upload.pic.type}")
private String picTypes;
public ReturnObject<Object> picUpload(MultipartFile file, String upLoadPath) {
String staticPath = environment.getProperty("spring.mvc.static-path-pattern");//img/**
String url = environment.getProperty("ai.domain") + "/" + staticPath.split("/")[1] + "/" + upLoadPath;
String originalFilename = file.getOriginalFilename();
log.info("原始文件名:" + originalFilename);
assert originalFilename != null;
String format = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
if (Arrays.asList(picTypes.split(",")).contains(format.toLowerCase())) {
String videoName = UUID.randomUUID().toString();
log.info("UUID文件名:" + videoName);
String dateOne = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd/"));//todo
String filePath;
if (StringUtils.endsWith("/", upfilePath)) filePath = upfilePath + upLoadPath + dateOne;
else filePath = upfilePath + "/" + upLoadPath + dateOne;
try {
Files.createDirectories(Path.of(filePath));
Files.write(Paths.get(filePath + videoName), file.getBytes());
} catch (Exception e) {
log.error(e.getMessage(), e);
}
List<String> urlList = new ArrayList<>();
urlList.add(url);
urlList.add(dateOne + videoName);
return new ReturnObject<>(ConstantOfReturnCode.GLOBAL_RESULT_SUCESS, "上传成功", urlList);
} else {
return new ReturnObject<>(ConstantOfReturnCode.GLOBAL_RESULT_FALSE, "该图片格式非法,请上传jpg,png,jpeg图片");
}
}
public ReturnObject<Object> picDownload(String url, HttpServletResponse response) {
File f = new File(url);
if (!f.exists())
return new ReturnObject<>(ConstantOfReturnCode.GLOBAL_RESULT_FALSE, "该图片不存在!");
byte[] bytes = new byte[1024];
BufferedInputStream bufferedInputStream = null;
OutputStream outputStream = null;
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(f);
bufferedInputStream = new BufferedInputStream(fileInputStream);
response.setContentType(MediaType.APPLICATION_OCTET_STREAM.toString());
response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(f.getName(), "UTF-8"));
outputStream = response.getOutputStream();
int length;
while ((length = bufferedInputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, length);
}
outputStream.flush();
} catch (Exception e) {
e.getLocalizedMessage();
} finally {
try {
if (bufferedInputStream != null) {
bufferedInputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
if (fileInputStream != null) {
fileInputStream.close();
}
} catch (IOException e) {
e.getLocalizedMessage();
}
}
return new ReturnObject<>(ConstantOfReturnCode.GLOBAL_RESULT_SUCESS, "下载成功!");
}
public static String getTomcatWabAppsPath() {
String tomcatRoot = Objects.requireNonNull(FileUploadUtils.class.getClassLoader().getResource("")).getPath();
String[] foo = tomcatRoot.split("/");
StringBuilder tomcatWebAppsBuilder = new StringBuilder();
int i = 0;
for (String paths : foo) {
++i;
if (i != foo.length) {
tomcatWebAppsBuilder.append(paths);
tomcatWebAppsBuilder.append("/");
}
}
return tomcatWebAppsBuilder.toString();
}
/**
* 多文件上传
*
* @param files
* @param filePath
* @return
*/
public String uploads(MultipartFile[] files, String filePath) {
if (files.length == 0) return "files.size=0";
for (MultipartFile file : files) {
try {
byte[] bytes = file.getBytes();
Path path = Paths.get(filePath + Objects.requireNonNull(file.getOriginalFilename()));
Files.write(path, bytes);
} catch (IOException e) {
log.error(e.getLocalizedMessage(), e);
return "unsuccessfully";
}
}
return "successfully";
}
public static String getIpAddress() {
try {
Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
while (allNetInterfaces.hasMoreElements()) {
NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
continue;
} else {
Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
ip = addresses.nextElement();
if (ip != null && ip instanceof Inet4Address) {
return ip.getHostAddress();
}
}
}
}
} catch (Exception e) {
System.err.println("IP地址获取失败" + e.toString());
}
return "";
}
}