javaWeb实现文件下载

Controller:

@Api(description = "文件管理", tags = "FileManage")
@RestController
@RequestMapping(value = "/v1/FileManage")
public class FileManageController {

    @Autowired
    private FileService fileService;

    @ApiOperation(value="文件下载")
    @PostMapping("/downloadFile")
    public void downloadFile(@RequestBody File file, HttpServletResponse resp) {

        fileService.downloadFile(file.getFilename(),file.getId()+"",resp);
    }
}

FileServiceImpl

@Service
@Transactional
public class FileServiceImpl implements FileService {
    
    /**
     * 下载文件
     */
    @Override
    public void downloadFile(String filename, String id, HttpServletResponse resp) {
        String orginFilePath = uploadPath + "/" +id + "/" + filename;
        File file = new File(orginFilePath);
        if (file.exists()) {
            InputStream inStream = null;
            BufferedOutputStream os = null;
            try {
                inStream = new FileInputStream(file);
                // 设置输出的格式,以附件的方式输出,不用用浏览器打开
                byte[] buffer = new byte[1024];
                int byteread;
                try {
                    resp.reset();
                    resp.addHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
                    resp.setContentType("application/octet-stream");
                    os = new BufferedOutputStream(resp.getOutputStream());
                    while ((byteread = inStream.read(buffer)) != -1) {
                        os.write(buffer, 0, byteread);
                    }
                    inStream.close();
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (inStream != null) {
                        inStream.close();
                    }
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                try {
                    if (os != null) {
                        os.close();
                    }
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        } else {
            resp.reset();
            try {
                resp.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("文件不存在", "UTF-8"));
                resp.setContentType("application/octet-stream");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }
}

 

 

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页