1. 程式人生 > >Java實現檔案下載

Java實現檔案下載

一、前臺通過a標籤開啟介面,傳入檔案id

<a href="/cdc/announcement/downloadFile/1">下載</a>

二、後臺接收id,查詢對應檔案,進行下載

    @RequestMapping(value = "downloadFile/{id}", method = RequestMethod.GET)
    @PreAuthorize("hasAuthority('view')")
    @ResponseBody
    public void downloadFile(HttpServletRequest req, HttpServletResponse resp, @PathVariable("id") Long id) {
        AnnouncementAnnex announcementAnnex = announcementAnnexService.selectById(id);
        //真實檔名
        String name = announcementAnnex.getAnnexUrl();
        String downloadName=announcementAnnex.getAnnexName();
//        進行轉碼後的檔名,用來下載之後的檔名
        PublicController.download(resp,name,downloadName);
    }

其中download方法
 /**
     * @param resp
     * @param name         檔案真實名字
     * @param downloadName 檔案下載時名字
     */
    public static void download(HttpServletResponse resp, String name, String downloadName) {
        String fileName = null;
        try {
            fileName = new String(downloadName.getBytes("GBK"), "ISO-8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        ///home/tomcat/apache-tomcat-9.0.1/files
        String realPath = "D:" + File.separator + "apache-tomcat-8.5.15" + File.separator + "files";
//        String realPath=File.separator+"home"+File.separator+"tomcat"+File.separator+"apache-tomcat-9.0.1"+File.separator+"files";
        String path = realPath + File.separator + name;
        File file = new File(path);
        resp.reset();
        resp.setContentType("application/octet-stream");
        resp.setCharacterEncoding("utf-8");
        resp.setContentLength((int) file.length());
        resp.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = resp.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(file));
            int i = 0;
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
                os.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
fileName是檔案下載之後的名字,filePath是檔案所在資料夾地址,path是檔案地址,注意設定的響應型別和編碼方式

其中File.separator為路徑分隔符,他能自動識別是哪個作業系統而使用不同的路徑分隔符(windows是‘\’,linux是‘/’)。