SSM 實現文件下載功能(用postman測試)


  1. 前端只用傳文件的路徑即可。 如:String path = “D:\user\test.docx”;
  2. controller
    @Autowired
    FileService fileService;
    /**
    * 前端傳文件路徑來下載文件
    *
    * @param path 文件路徑,如 /guide/appendix.doc
    * @param response
    * @return
    */
    @RequestMapping(value = "/download")
    @ResponseBody
    public CommonReturnType downloadAppendix(@Param("path") String path, HttpServletRequest request, HttpServletResponse response) {
    fileService.downloadFile(path,request,response);
    return CommonReturnType.create(null, "下載完成");
    }
  3. service
    @Override
    public void downloadFile(String path, HttpServletRequest request, HttpServletResponse response) {
    try {
    //String pathTest = "D:\\UPC\\offer"+"\\"+fileName;
    //轉碼,免得文件名中文亂碼(有時候加上反而會亂碼)
    // fileName = URLEncoder.encode(fileName,"UTF-8");

    //從路徑中獲取文件名稱,trim:去除字符串前后的空格
    File tempFile = new File(path.trim());
    String filename = tempFile.getName();

    //解決中文文件名亂碼
    String userAgent = request.getHeader("User-Agent");
    //IE內核瀏覽器
    if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
    filename = java.net.URLEncoder.encode(filename, "UTF-8");
    } else {
    // 非IE瀏覽器的處理:
    filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1");
    }
    //設置文件下載頭
    response.setHeader("Content-disposition",String.format("attachment; filename=\"%s\"", filename));
    //設置文件ContentType類型,這樣設置,會自動判斷下載文件類型
    response.setContentType("multipart/form-data");
    response.setCharacterEncoding("UTF-8");

    InputStream inputStream = new BufferedInputStream(new FileInputStream(new File(path)));
    BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
    //創建緩沖區
    byte[] buffer = new byte[1024];
    int length;
    while ((length = inputStream.read(buffer)) != -1) {
    outputStream.write(buffer, 0, length);
    outputStream.flush();
    }
    //關閉流
    inputStream.close();
    outputStream.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
  4. postman測試

     

     本人完整調試,簡單標准實現文件下載


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM