本文共 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/