@GetMapping("download") @ApiOperation(value = "下载 标准库板块excel") public void download(HttpServletRequest request, HttpServletResponse response) { OutputStream os = null; InputStream inputStream = null; BufferedInputStream bis = null; try { ResourceLoader resourceLoader = new DefaultResourceLoader(); String fileTemplateName = "标准库板块.xlsx"; inputStream = resourceLoader.getResource("classpath:/templatefile/"+fileTemplateName).getInputStream(); bis = new BufferedInputStream(inputStream); os = response.getOutputStream(); //通过文件名称获取MIME类型 String framename = filenameEncoding(fileTemplateName, request); String contentType = request.getServletContext().getMimeType(fileTemplateName); String contentDisposition = "attachment;filename=" + framename; response.setHeader("Content-Type", contentType); response.setHeader("Content-Disposition", contentDisposition); byte[] buffer = new byte[1024]; int i = bis.read(buffer); while (i != -1) { os.write(buffer, 0, i); i = bis.read(buffer); } } catch (Exception ue) { throw new CommonException("下载 标准库板块失败!", ue); }finally { try { os.close(); inputStream.close(); bis.close(); }catch (Exception ue){ throw new CommonException("下载 标准库板块失败!", ue); } } } private String filenameEncoding(String filename, HttpServletRequest request){ try { String agent = request.getHeader("User-Agent"); //获取浏览器 if (agent.contains("Firefox")) { filename = "=?" + "UTF-8" + "?B?" + Base64.encodeBase64String(filename.getBytes("UTF-8")) + "?="; } else if(agent.contains("MSIE")) { filename = URLEncoder.encode(filename, "UTF-8"); } else { filename = URLEncoder.encode(filename, "UTF-8"); } } catch (Exception e) { throw new CommonException("文件名转换异常!", e); } return filename; }
标签:String,request,filename,resources,new,服务器,fileTemplateName,bis,下载 From: https://www.cnblogs.com/chenTo/p/17340817.html