标签:远程服务器文件流下载 文件流下载 流下载
/** * 远程服务下载类 * * @author jiyanle. * @date 2015/6/17 */ @Controller @RequestMapping(value = "download") public class FileDownload extends BaseController { /** * 远程服务器文件下载 * * @param request * @param response * @param fileDir 文件目录,相对于根目录 * @param fileName 指定下载保存后的文件名(含扩展名) * @return */ @RequestMapping(value = "downloadFile") public String downloadFile(HttpServletRequest request, HttpServletResponse response, String fileDir, String fileName) { PrintWriter out = null; // 目标远程服务器文件地址 String path = GlobalConfig.getImgServer() + "/" + fileDir; try { out = response.getWriter(); File file = new File(path); // 以流的形式下载文件。 URL url = new URL(path); HttpURLConnection uc = (HttpURLConnection) url.openConnection(); uc.connect(); // 远程服务器调用 InputStream fis = new BufferedInputStream(uc.getInputStream()); //url.openStream(); //new BufferedInputStream(new FileInputStream(path));//本地服务器调用 byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); // 清空response response.reset(); response.setCharacterEncoding("utf-8"); //解决各浏览器的中文乱码问题 String userAgent = request.getHeader("User-Agent"); byte[] bytes = userAgent.contains("MSIE") ? fileName.getBytes() : fileName.getBytes("UTF-8"); // fileName.getBytes("UTF-8")处理safari的乱码问题 fileName = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码 response.addHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", fileName)); //"attachment;filename=" + toUtf8String(fileName)); response.addHeader("Content-Length", "" + uc.getHeaderField("Content-Length")); response.setContentType("application/octet-stream"); OutputStream toClient = new BufferedOutputStream(response.getOutputStream()); toClient.write(buffer); toClient.flush(); toClient.close(); } catch (Exception e) { if (e instanceof FileNotFoundException) { out.print("服务器文件丢失!"); } else { out.print("下载异常"); } } return null; } }
本文出自 “猪会飞” 博客,请务必保留此出处http://jiyanle.blog.51cto.com/6932197/1677454
标签:远程服务器文件流下载 文件流下载 流下载
原文地址:http://jiyanle.blog.51cto.com/6932197/1677454