比如說,下載的文件名為: 軟件分析報告.docx,當使用流拋給瀏覽器下載時,瀏覽器下載的文件為:-----------.docx
出現這種情況的原因:大體的原因就是header中只支持ASCII,所以我們傳輸的文件名必須是ASCII,所以說當文件名為中文時,必須要將該中文轉換成ASCII。
// 文件名可以任意指定 response.setHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(filename,"UTF-8"));
其中 URLEncoder.encode(filename,"UTF-8") 就是將文件名轉為ASCLL
java實現瀏覽器下載:
public void downloadFile(String id, HttpServletResponse response) { if(!StringUtils.isEmpty(id)) { GridFSDBFile gridFSDBFile = dynamicService.getGridFSDBFile(Integer.parseInt(id));//從mongodb上獲取文件信息 int buffer = 1024 * 10; byte data[] = new byte[buffer]; InputStream inputStream = gridFSDBFile.getInputStream();//獲取輸入流 BufferedInputStream bis = new BufferedInputStream(inputStream, buffer); try { String filename = gridFSDBFile.getFilename(); response.setContentType(FileUtils.getContentType(filename)); // 文件名可以任意指定 response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename,"UTF-8"));//將文件名轉為ASCLL編碼 int read; while ((read = bis.read(data)) != -1) { response.getOutputStream().write(data, 0, read); } inputStream.close(); bis.close(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
