最近做项目的时候要做一个下载功能,这个下载的文档在公司的其他服务器上也有,所以我开始时我并不想在本地服务器上存储文件,后来试过一次放在本地,本地环境是linux,测试的时候不知道为啥文档名是中文的时候程序总是报错,文档名也编码了,总之就是不知道为什么中文的不行,如果有大神知道请赐教。
后来还是尝试用HttpURLConnection远程下载文件,存储文件的那台服务器是windows。以下是部分源码,也参考网上的代码,请参考。
public void doFileDownload(String fileName, String fileSaveRootPath, HttpServletRequest request, HttpServletResponse response) { String message = "success"; //fileName = "tanhao.png"; try { String fileurl = "http://" + fileSaveRootPath + URLEncoder.encode(fileName,"UTF-8").replace("+"," "); ; //String fileurl = "http://服务器ip/files/document/用户.txt" ; URL url = new URL(fileurl); HttpURLConnection urlc = (HttpURLConnection) url.openConnection(); urlc.setRequestProperty("Content-type","application/x-www-form-urlencoded;charset=UTF-8"); urlc.setRequestProperty("Accept-Language", "zh-CN"); // 设置字符编码 urlc.setRequestProperty("Charset", "UTF-8"); String realname = fileName; //将文件读入文件流 InputStream inStream = urlc.getInputStream(); //设置浏览器代理信息 String agent = request.getHeader("USER-AGENT"); //判断浏览器代理并分别设置响应给浏览器的编码格式 String finalFileName = null; if(agent != null && agent.indexOf("MSIE") == -1) {// FF realname = "=?UTF-8?B?" + (new String(Base64.encodeBase64(realname.getBytes("UTF-8")))) + "?="; response.setHeader("content-disposition", "attachment;filename=" + realname); } else { // IE response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(realname, "UTF-8")); } // 循环取出流中的数据 byte[] b = new byte[1024]; int len; while ((len = inStream.read(b)) > 0){ response.getOutputStream().write(b, 0, len); } inStream.close(); response.getOutputStream().close(); urlc.disconnect(); logger.info("============下载成功了!!==========="); }catch(Exception e) { e.printStackTrace(); logger.info("==========下载出错了!!==========="); } }