修复使用http文件流下载时文件名编码异常Gitee-#I4W0TQ
parent
051ad0f4ea
commit
ba7b6eed4a
|
@ -115,10 +115,22 @@ public class WebUtils {
|
|||
* @return 文件名编码后的url
|
||||
*/
|
||||
public static String encodeUrlFileName(String url) {
|
||||
String encodedFileName;
|
||||
String fullFileName = WebUtils.getUrlParameterReg(url, "fullfilename");
|
||||
if (fullFileName != null && fullFileName.length() > 0) {
|
||||
try {
|
||||
encodedFileName = URLEncoder.encode(fullFileName, "UTF-8");
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
return null;
|
||||
}
|
||||
String noQueryUrl = url.substring(0, url.indexOf("?"));
|
||||
String parameterStr = url.substring(url.indexOf("?"));
|
||||
parameterStr = parameterStr.replaceFirst(fullFileName, encodedFileName);
|
||||
return noQueryUrl + parameterStr;
|
||||
}
|
||||
String noQueryUrl = url.substring(0, url.contains("?") ? url.indexOf("?") : url.length());
|
||||
int fileNameStartIndex = noQueryUrl.lastIndexOf('/') + 1;
|
||||
int fileNameEndIndex = noQueryUrl.lastIndexOf('.');
|
||||
String encodedFileName;
|
||||
try {
|
||||
encodedFileName = URLEncoder.encode(noQueryUrl.substring(fileNameStartIndex, fileNameEndIndex), "UTF-8");
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
|
|
|
@ -21,4 +21,12 @@ public class WebUtilsTests {
|
|||
String out = "https://file.keking.cn/demo/%23hello%26world.txt?param0=0¶m1=1";
|
||||
assert WebUtils.encodeUrlFileName(in).equals(out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void encodeUrlFullFileNameTestWithParams() {
|
||||
// 测试对URL中使用fullfilename参数的文件名部分进行UTF-8编码
|
||||
String in = "https://file.keking.cn/demo/download?param0=0&fullfilename=hello#0.txt";
|
||||
String out = "https://file.keking.cn/demo/download?param0=0&fullfilename=hello%230.txt";
|
||||
assert WebUtils.encodeUrlFileName(in).equals(out);
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue