Java下载文件
Posted 尚荣伊翁
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java下载文件相关的知识,希望对你有一定的参考价值。
public void downloadFile(){ String filePath = request.getParameter("filepath"); try { filePath = new String(filePath.getBytes("ISO-8859-1"),"UTF-8"); String rootPath = request.getSession().getServletContext().getRealPath("/"); File file = new File(rootPath+filePath); String downFileName = file.getName(); InputStream fis = new BufferedInputStream(new FileInputStream(file)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); // 清空response response.reset(); // 设置response的Header response.addHeader("Content-Disposition", "attachment;filename=" + new String(downFileName.getBytes())); response.addHeader("Content-Length", "" + file.length()); OutputStream toClient = new BufferedOutputStream(response.getOutputStream()); response.setContentType("application/octet-stream"); toClient.write(buffer); toClient.close(); } catch (Exception e) { log.errorLog("文件下载失败", e); } }
以上是关于Java下载文件的主要内容,如果未能解决你的问题,请参考以下文章