项目总结_servlet中文下载时乱码中文文件名不能显示
response.setContentType("application/x-msdownload"); // response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename="+ new String(fileName.getBytes("utf-8"),"ISO-8859-1"));
原因分析,由于HTTP头部的默认编码为ISO-8859-1而我们上传文件于下载文件过程中,提取到的文件名都要通过HTTP头部。
所以我们需要在上传的时候对提取到的文件名进行转码为UTF-8,然后在下载时我们也要进行反向转码为ISO-8859-1.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); String realPath = request.getParameter("realPath"); String filename= new String(request.getParameter("filename").getBytes("ISO-8859-1"),"utf-8"); OutputStream out = response.getOutputStream(); File file = new File(realPath+File.separator+filename); FileInputStream in = null; byte[] bytes = new byte[1024]; if(file.exists()){ // response.setHeader("Content-disposition", "attachment;filename="+ filename); //response.setContentType("application/x-tar"); //response.setContentType("application/x-msdownload"); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=\"" + new String(filename.getBytes("utf-8"),"ISO-8859-1" )+ "\""); long fileLength = file.length(); String length = String.valueOf(fileLength); response.setHeader("Content_Length", length); in = new FileInputStream(file); int n = 0; while ((n = in.read(bytes)) != -1) { out.write(bytes, 0, n); } out.close(); }else{ /* PrintWriter writer = response.getWriter(); writer.println("找不到指定文件,或文件已经删除"); writer.close();*/ System.out.println("找不到指定文件,或文件已经删除"); } }