我想根据用户选择下载office文件,pdf文件,image文件,zip文件,dll文件,exe文件。因此,我想从jsp页面下载这些文件类型。
这是jsp代码片段:
<% String filename = "Sample1.docx"; String filepath = "e:\\temp\\"; response.setContentType("APPLICATION/OCTET-STREAM"); response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\""); java.io.FileInputStream fileInputStream = new java.io.FileInputStream(filepath + filename); int i; while ((i=fileInputStream.read()) != -1) { out.write(i); } fileInputStream.close(); %>
但是在下载Office文件,图像文件时,它会引起一些错误。当我打开下载的文件时,它显示“文件可能已损坏”。
有什么通用的方法可以在jsp中下载所有类型的文件?
好的,从其他浏览器下载文件时会出现一些问题。我的示例照顾了MSIE和Mozilla类型的浏览器中所需的处理
public HttpServletResponse getFile (HttpServletRequest request ,HttpServletResponse httpServletResponse, .......){ HttpServletResponse response = httpServletResponse; InputStream in =/*HERE YOU READ YOUR FILE AS BinaryStream*/ String filename = ""; String agent = request.getHeader("USER-AGENT"); if (agent != null && agent.indexOf("MSIE") != -1) { filename = URLEncoder.encode(/*THIS IS THE FILENAME SHOWN TO THE USER*/, "UTF8"); response.setContentType("application/x-download"); response.setHeader("Content-Disposition","attachment;filename=" + filename); } else if ( agent != null && agent.indexOf("Mozilla") != -1) { response.setCharacterEncoding("UTF-8"); filename = MimeUtility.encodeText(/*THIS IS THE FILENAME SHOWN TO THE USER*/, "UTF8", "B"); response.setContentType("application/force-download"); response.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); } BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream()); byte by[] = new byte[32768]; int index = in.read(by, 0, 32768); while (index != -1) { out.write(by, 0, index); index = in.read(by, 0, 32768); } out.flush(); return response; }
看一下这个
更新