01 文件下载编码问题
Posted meitanzai
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了01 文件下载编码问题相关的知识,希望对你有一定的参考价值。
/** * 文件下载 * * @param id * @param basePath * @param response * @throws Exception */ @RequestMapping(value = "/file_download", method = { RequestMethod.POST,RequestMethod.GET }) public void downloadCommon(String id, HttpServletRequest request, HttpServletResponse response) throws Exception { //调用ServletOutputStream或者Writer之前有效。 //当使用的缓存已满时,容器必须立刻刷新把缓存的内容发送到客户端,如果这是第一个被发送到客户端的数据,那么response也会被认为是已提交 response.reset(); response.setHeader("Content-Type", "application/force-download"); String encode = request.getParameter("encode"); if (encode != null && !"".equals(encode)) { try { request.setCharacterEncoding(ENCODING); } catch (UnsupportedEncodingException e) { request.setCharacterEncoding(ENCODING); } } else { request.setCharacterEncoding(ENCODING); } String path = null; String fileName=null; String saveFileName=null; InputStream input =null; OutputStream output = null; try { // 构建流 input = new FileInputStream(path + File.separator + fileName); output =response.getOutputStream();
if(request.getHeader("user-agent").indexOf("MSIE") != -1 || request.getHeader("user-agent").indexOf("like Gecko")!=-1) { saveFileName = java.net.URLEncoder.encode(saveFileName,ENCODING); } else { saveFileName = new String(saveFileName.getBytes(ENCODING),"iso-8859-1"); } //在response被提交前,头信息必须被设置,否则无效 //Content-Disposition 设置文件名,文件名有空格时下载文件名错误的解决办法 \fileName\ response.setHeader("Content-disposition", "inline;filename=\"" +saveFileName+"\""); // 输出文件流 byte[] buffer = new byte[1024]; int i = 0; while ((i = input.read(buffer)) != -1) { output.write(buffer, 0, i); } } catch (Exception e) { //TODO } finally { try { if(null !=output) { output.flush(); output.close(); } if(null !=input) { input.close(); } } catch (Exception e) { } } }
以上是关于01 文件下载编码问题的主要内容,如果未能解决你的问题,请参考以下文章
《安富莱嵌入式周报》第279期:强劲的代码片段搜索工具,卡内基梅隆大学安全可靠C编码标准,Nordic发布双频WiFi6 nRF7002芯片