博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java下载文件中文乱码情况解决方法
阅读量:4137 次
发布时间:2019-05-25

本文共 1777 字,大约阅读时间需要 5 分钟。

@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 block				e.printStackTrace();			} catch (IOException e) {				// TODO Auto-generated catch block				e.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;		  }	}

获取路径的方法:

InputStream path = TestDemo.class.getClassLoader().getResourceAsStream("../down/js.pdf");
String path = TestDemo.class.getResource(“/test.txt”).getPath();
String path = Thread.currentThread().getContextClassLoader().getResource("/js.pdf").getFile();
String path = request.getSession().getServletContext().getRealPath("down/js.psd");
 
 
 

转载地址:http://npxvi.baihongyu.com/

你可能感兴趣的文章
HDU 1075 What Are You Talking About(map+字符串)
查看>>
HDU 2600 War(水题 区间边排序+贪心)
查看>>
HDU 1175 连连看(DFS)
查看>>
HDU 1180 诡异的楼梯(BFS+奇偶步数判断)
查看>>
HDU 2709 Sumsets(DP递推)
查看>>
HDU 5443 The Water Problem(线段树水题)
查看>>
HDU 5438 Ponds(2015ACM长春网络赛+枚举删点+DFS求联通块)
查看>>
HDU 5437 Alisha’s Party(2015ACM长春赛区网络赛+优先队列)
查看>>
HDU 5461 Largest Point(2015沈阳赛区网络赛+技巧水题)
查看>>
HDU 5464 Clarke and problem(DP 01背包)
查看>>
HDU 5455 Fang Fang(2015沈阳赛区网络赛)
查看>>
HDU 2571 命运(DP)
查看>>
HDU 2955 Robberies(01背包+概率)
查看>>
HDU 1203 I NEED A OFFER!(01背包+概率)
查看>>
HDU 1238 Substrings(求公共正反向连续子串)
查看>>
HDU 2717 Catch That Cow(哎!居然没想到用bfs)
查看>>
HDU 25919 新生晚会(水题组合问题)
查看>>
HDU 2612 Find a way(两次bfs)
查看>>
HDU 2188 选拔志愿者(简单博弈+记忆化)
查看>>
HDU 5493 Queue(线段树)
查看>>