@Value("${file.path}")
private String dirPath;
@ResponseBody
@PostMapping("/upload")
@ApiOperation(value = "文档/文件上传")
public ApiResult<?> upload(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return ApiResult.error("上传失败,请选择文件");
}
File defFileDir = new File(dirPath);
if (!defFileDir.exists()) {
boolean isMkSuccess = defFileDir.mkdirs();
}
String prefix;
try {
prefix = Objects.requireNonNull(file.getOriginalFilename())
.substring(file.getOriginalFilename().lastIndexOf("."));
} catch (Exception e) {
prefix = ".png";
}
String fileName = UUID.randomUUID() + prefix;
String newFilePath = dirPath + File.separator + fileName;
try {
file.transferTo(new File(newFilePath));
return generateUrlApiResult(fileName);
} catch (IOException e) {
e.printStackTrace();
return ApiResult.error("上传失败");
}
}
// ServletUriComponentsBuilder contextPath = ServletUriComponentsBuilder.fromCurrentContextPath();
// String currentHost = contextPath.build().getHost();
// if ("localhost".equals(currentHost)) {
// String ipHostAddress = "";
// try {
// Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
// while (allNetInterfaces.hasMoreElements()) {
// NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
// Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
// while (addresses.hasMoreElements()) {
// InetAddress ip = (InetAddress) addresses.nextElement();
// if (ip instanceof Inet4Address
// && !ip.isLoopbackAddress() //loopback地址即本机地址,IPv4的loopback范围是127.0.0.0 ~ 127.255.255.255
// && !ip.getHostAddress().contains(":")) {
// System.out.println(ip.getHostAddress());
// ipHostAddress = ip.getHostAddress();
// }
// }
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// contextPath.host(ipHostAddress);
// }
//
// String fileDownloadUri = contextPath
// .path(File.separator + fileName)
// .toUriString();
// HashMap<String, String> responseMap = new HashMap<>();
// responseMap.put("url", fileDownloadUri);
// return ApiResult.success(responseMap);
网友评论