java 獲取服務器文件,直接下載到瀏覽器

一、聲明

注意參數要有HttpServletResponse response並設置參數

response.setContentType("application/application/vnd.ms-excel");
response.setHeader("Content-disposition","attachment;filename=" + fileName);

@RequestMapping(value = "downloadZip", method = RequestMethod.GET)
    public void downloadZip(HttpServletResponse response,String id) throws Exception {
        String fileName=workCardPhotoFileService.downloadZipFile(id);
        if (StringUtils.isNotEmpty(fileName)){
            response.setContentType("application/application/vnd.ms-excel");
            response.setHeader("Content-disposition",
                    "attachment;filename=" + fileName);
            download(response.getOutputStream(),fileName);
        }


    }
 public void download(OutputStream os, String fileName) throws IOException {
        //獲取服務器文件
        File file = new File("/Users/Desktop/download/workcardphoto/"+fileName);

        InputStream ins = new FileInputStream(file);
        byte[] b = new byte[1024];
        int len;
        while((len = ins.read(b)) > 0){
            os.write(b,0,len);
        }
        os.flush();
        os.close();
        ins.close();
    }

結束~感謝觀看

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章