天天看點

Springboot 從伺服器上下載下傳檔案

學習自 https://www.cnblogs.com/luzhanshi/p/12360495.html

controller層代碼

@RequestMapping("/download")
    public Map<String,String> download(HttpServletRequest request,HttpServletResponse response,String fileName) throws UnsupportedEncodingException {
        Map<String,String> map = new HashMap<>();
        String rootPath = System.getProperty("user.dir")+"\\src\\main\\resources\\uploadFile\\";//存儲檔案的目錄
        String FullPath = rootPath + fileName;//檔案的位置
        File packetFile = new File(FullPath);
        String fn = packetFile.getName(); //下載下傳的檔案名
        System.out.println("filename:"+fn);
        File file = new File(FullPath);
        // 如果檔案名存在,則進行下載下傳
        if (file.exists()) {
            // 配置檔案下載下傳
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            // 下載下傳檔案能正常顯示中文
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            // 實作檔案下載下傳
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                System.out.println("Download the song successfully!");
            } catch (Exception e) {
                System.out.println("Download the song failed!");
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return null;
        } else {//對應檔案不存在
            map.put("result","failed");
            return map;
        }

    }
           

前端代碼

function  downloadFile(fileName){
    window.open("/meeting/download?fileName="+fileName);
}