java下载文件中文乱码情况解决方法

来源:互联网 发布:fifaonline317卡数据 编辑:程序博客网 时间:2024/06/05 10:53
@RequestMapping(value="/downfile",method=RequestMethod.GET)public String download(String filename,HttpServletRequest req,HttpServletResponse res) throws UnsupportedEncodingException{filename = new String(filename.getBytes("iso-8859-1"),"utf-8"); System.out.println(filename+"******");String realpath=req.getSession().getServletContext().getRealPath("down");File file = new File(realpath+"/"+filename);if(file.exists()){//下载  读 输入流 ---》(写响应流)客户端res.setContentType("application/octet-stream"); String headerValue = "attachment;";  headerValue += " filename=\"" + encodeURIComponent(filename) +"\";";  headerValue += " filename*=utf-8''" + encodeURIComponent(filename);res.addHeader("Content-Disposition", headerValue);try {FileInputStream is=new FileInputStream(file);byte[] arr=new byte[is.available()];is.read(arr);//写到响应流OutputStream os=res.getOutputStream();os.write(arr);os.close();is.close();} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return "downsucc";}public static String encodeURIComponent(String value) {  try {    return URLEncoder.encode(value, "UTF-8").replaceAll("\\+", "%20");  } catch (UnsupportedEncodingException e) {    e.printStackTrace();    return null;  }}

原创粉丝点击