SpringBoot下載文件


 

@GetMapping(value = "/downOrderTemplate")
    public ObjectRestResponse<String> downOrderTemplate() throws IOException {
//        String rootPath = System.getProperty("user.dir");
//        log.info("======rootPath==="+rootPath);
//        File file = new File(rootPath.replace("\\","/")+"/src/main/resources/template/orderTemplate.xlsx");
        ClassPathResource resource = new ClassPathResource("template/orderTemplate.xlsx");
        InputStream inputStream = resource.getInputStream();
//        File file = resource.getFile();
        File file = new File("orderTemplate.xlsx");
        try (FileOutputStream outputStream = new FileOutputStream(file)) {
            int read;
            byte[] bytes = new byte[1024];
            while ((read = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, read);
            }
        }
        if(!file.exists()){
            return new ObjectRestResponse<String>().rel(true).data("下載導入模板文件不存在");
        }
        response.reset();
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "attachment;filename=orderTemplate.xlsx");

        try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));) {
            byte[] buff = new byte[1024];
            OutputStream os  = response.getOutputStream();
            int i = 0;
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
                os.flush();
            }
        } catch (IOException e) {
            log.error("{}",e);
            return new ObjectRestResponse<String>().rel(true).data("下載失敗");
        }
        return new ObjectRestResponse<String>().rel(true).data("下載成功");
    }

 


免責聲明!

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



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