java上传下载文件,中文文件名不显示或乱码

时间:2021-08-31 20:57:53

参考这里:https://my.oschina.net/pingpangkuangmo/blog/376332

上传文件页面:

<body>
<form method="post" action="${pageContext.request.contextPath }/fileUpload" enctype="multipart/form-data">
选择一个文件:
<input type="file" name="uploadFile" />
<br/><br/>
<input type="submit" value="上传" />
</form>
</body>

上传文件后,由springmvc处理请求:

/**
* 上传文件
* @param file
* @throws IOException
*/
@RequestMapping("/fileUpload")
public ModelAndView fileUpload(@RequestParam("uploadFile") CommonsMultipartFile file) {
//获取文件名称
String fileName = file.getOriginalFilename();
//保存文件
File tempfile = new File("E:/zzhtml/"+fileName);
OutputStream os = null;
InputStream is = null;
try {
is = file.getInputStream();
byte[] bs = new byte[1024];
int len;
os = new FileOutputStream(tempfile);
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
if(os!=null){
os.close();
}
if(is!=null){
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
ModelAndView mv = new ModelAndView("uploadSuccess");
mv.addObject("fileName", fileName);
return mv;
}

下载文件页面:

<body>
上传成功<br><a href="${pageContext.request.contextPath }/fileDown?fileName=${fileName}">${fileName }</a>
</body>

点击下载文件,后台处理:

@RequestMapping("/fileDown")
public String fileDown(@RequestParam("fileName")String fileName,HttpServletResponse response) throws UnsupportedEncodingException{
String path="E:/zzhtml/";
String tempFileName = new String(fileName.getBytes("ISO8859-1"), "UTF-8");
//1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
response.setContentType("application/x-msdownload");
//2.设置文件头:最后一个参数是设置下载文件名(假如我们叫a.pdf)
response.setHeader("Content-Disposition", "attachment;fileName="+new String(tempFileName.getBytes("GBK"),"ISO8859-1")); //这里的fileName要是ISO8859-1编码
ServletOutputStream out = null;
FileInputStream is = null ;
//通过文件路径获得File对象
File file = new File(path +tempFileName);
try {
is= new FileInputStream(file);
//3.通过response获取ServletOutputStream对象(out)
out = response.getOutputStream();
int b = 0;
byte[] buffer = new byte[1024];
while ((b=is.read(buffer,0,buffer.length))!= -1){
//4.写到输出流(out)中
out.write(buffer,0,b);
}
out.flush();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(is!=null){
is.close();
}
if(out!=null){
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}