《通过http下载文件,并修改名称》处理重复的后缀

This commit is contained in:
guoshengxiong 2025-09-27 16:45:57 +08:00
parent 3cca4e4a1c
commit 1e38b52511

View File

@ -105,15 +105,21 @@ public class UploadFileController {
public void getRenameFile(@RequestParam("fileUrl") String fileUrl, @RequestParam("fileName") String fileName, HttpServletResponse response) { public void getRenameFile(@RequestParam("fileUrl") String fileUrl, @RequestParam("fileName") String fileName, HttpServletResponse response) {
try { try {
URL url = new URL(fileUrl); URL url = new URL(fileUrl);
int index = fileUrl.indexOf("?");//第一个问号的位置 // 清理URL参数
int index = fileUrl.indexOf("?");
if (index > -1) { if (index > -1) {
fileUrl = fileUrl.substring(0, index); fileUrl = fileUrl.substring(0, index);
} }
String[] split = fileUrl.split("\\."); // 从URL获取文件扩展名
// 不同文件的MimeType参考后续链接 String fileExtension = getFileExtension(fileUrl);
// 检查fileName是否已包含扩展名
String finalFileName = fileName;
if (!fileName.toLowerCase().endsWith("." + fileExtension.toLowerCase())) {
finalFileName = fileName + "." + fileExtension;
}
response.setContentType("application/x-download");//下面三行是关键代码处理乱码问题 response.setContentType("application/x-download");//下面三行是关键代码处理乱码问题
response.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "iso8859-1") + "." + split[split.length - 1]); response.setHeader("Content-Disposition", "attachment;filename=" + new String(finalFileName.getBytes("utf-8"), "iso8859-1"));
URLConnection conn = url.openConnection(); URLConnection conn = url.openConnection();
InputStream inStream = conn.getInputStream(); InputStream inStream = conn.getInputStream();
OutputStream fos = response.getOutputStream(); OutputStream fos = response.getOutputStream();
@ -123,10 +129,25 @@ public class UploadFileController {
response.getOutputStream().close(); response.getOutputStream().close();
response.flushBuffer(); response.flushBuffer();
} catch (Exception e) { } catch (Exception e) {
log.error("err:", e); log.error("下载文件失败:", e);
} }
} }
// 提取文件扩展名的辅助方法
private String getFileExtension(String fileUrl) {
String cleanUrl = fileUrl;
int queryIndex = fileUrl.indexOf("?");
if (queryIndex > -1) {
cleanUrl = fileUrl.substring(0, queryIndex);
}
int lastDotIndex = cleanUrl.lastIndexOf(".");
if (lastDotIndex > -1 && lastDotIndex < cleanUrl.length() - 1) {
return cleanUrl.substring(lastDotIndex + 1);
}
return ""; // 如果没有扩展名返回空字符串
}
@OperLog(operModul = "转换图片成webp格式", operType = "", operDesc = "转换图片成webp格式") @OperLog(operModul = "转换图片成webp格式", operType = "", operDesc = "转换图片成webp格式")
@PostMapping("/convertBase642webp") @PostMapping("/convertBase642webp")
public Result<String> convertBase642webp(@RequestBody Map<String, String> request, public Result<String> convertBase642webp(@RequestBody Map<String, String> request,