Spring mvc下載文件時報錯替代方式

/**
     * 下載文件
     */

    @GetMapping("/download")
    @ResponseBody
    public void downloadFile(String id,  HttpServletResponse response) throws IOException {
        Optional<OssFile> file = fileService.getFileById(id);
        if (file.isPresent()) {
            //設置文件輸出類型
            response.setContentType(file.get().getContentType());
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename="
                    + new String(file.get().getName().getBytes("utf-8"), "ISO8859-1"));
            //設置輸出長度
            response.setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf( file.get().getContent().length() ) );
            //輸出流
            byte[] buff = file.get().getContent().getData();
            IOUtils.write( buff,response.getOutputStream() );
        } else {
            response.getWriter().write( "OssFile was not fount" );
        }


    }
相關文章
相關標籤/搜索