Spring MVC控制器下载不了含有中文名的文件

youyiyang 2018-09-28 03:22:09
我在用Spring MVC开发一个上传和下载文件的控制器时,碰到如果下载含有中文名的文件时,因为传到控制器的中文名是乱码,所以下载的时候不能把正确的文件下载下来。
代码如下所示:

@RequestMapping(value="/{fileName:.+}/download.do")
public void downloadPDFResource( HttpServletRequest request,
HttpServletResponse response,
@PathVariable("fileName") String fileName
) throws UnsupportedEncodingException
{

String basepath="E:/HTML/SpringMVC/wtpwebapps/Upload/fileupload";
//If user is not authorized - he should be thrown out from here itself

//Authorized user will download the file

System.setProperty("Log4jContextSelector","org.apache.logging.log4j.core.async.AsyncLoggerContextSelector");

System.out.println("call downloading file");

HttpSession session = request.getSession();
String username = session.getAttribute("username").toString();
String firstname = session.getAttribute("firstname").toString();
String dataDirectory =basepath+"/"+username;
Path file = Paths.get(dataDirectory, fileName);
if (Files.exists(file))
{
response.setContentType("multipart/form-data");
response.addHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
try
{
Files.copy(file, response.getOutputStream());
response.getOutputStream().flush();
}
catch (IOException ex) {
ex.printStackTrace();
}
}else{
System.out.println(dataDirectory+"/"+fileName);
}
}

public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}

比如如果是中文名的文件时候,我把它打印在Console上如下所示:

E:/HTML/SpringMVC/wtpwebapps/Upload/fileupload/monkeyking123/????????????????????????è??????????¨?¤?????¤???é????¨è???????????.mp4

因为是 乱码所以下载不了。
我已经在配置文件里面加上了中文的过滤,但是好像不是这个原因,请问这个问题应该如何解决?
...全文
264 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
这个转码要注意只能对中文部分转码,防止将其他的非中文的如/之类的也被转码
User_undefined 2018-09-28
  • 打赏
  • 举报
回复
先url转码,进入Controller后再URL解码

67,512

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧