发送压缩文件Spring

时间:2017-07-31 14:54:57

标签: java spring http spring-mvc zip

我想通过我的Spring控制器发送一个已经存在的压缩文件,但我不断收到这些错误消息org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representationNoHandlerFoundException,这会导致404响应。有什么东西我错过了吗?这是我的控制器代码

@RequestMapping(
        method = RequestMethod.GET,
        value = BASE + "/download",
        produces = "application/zip"
)
@ResponseBody
public void sendZippedFile(HttpServletResponse response) throws IOException {
    try{
        File file = new File("C:\\Users\\me\\test.zip");
        FileInputStream is = new FileInputStream(file);
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition","inline; filename=" + file.getName());
        response.setHeader("Content-Length", String.valueOf(file.length()));
        FileCopyUtils.copy(is, response.getOutputStream());
    }catch (IOException e){
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
}

我的方法中的断点甚至都没有达到。

1 个答案:

答案 0 :(得分:1)

你需要这样的东西:

@RequestMapping("/download")
public void download(HttpServletResponse response) throws IOException {

        FileInputStream inputStream = new FileInputStream(new File("C:\\Users\\me\\test.zip"));

        response.setHeader("Content-Disposition", "attachment; filename=\"test.zip\"");
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);

        ServletOutputStream outputStream = response.getOutputStream();
        IOUtils.copy(inputStream, outputStream);

        outputStream.close();
        inputStream.close();
}