用于下载文件的rest api会返回文件内容作为响应,而无需下载文件

时间:2018-07-27 07:43:19

标签: java rest file download

    @GET
        @Path("/{loginId}")
        @Produces(MediaType.APPLICATION_OCTET_STREAM)
        public Response downloadExportedFile(@PathParam("loginId") String loginId) {
                File file = new File("D://abc.txt");
            Response.ResponseBuilder response = Response.ok((Object) file);
            response.header("Content-Disposition", "attachment; filename=newfile.txt");
response.type(MediaType.APPLICATION_OCTET_STREAM_TYPE);
            return response.build();
        }

这将响应作为文件的内容而不是下载

2 个答案:

答案 0 :(得分:0)

莫妮卡(Monika),如果您使用Spring,我建议返回带有这样标题的响应实体资源

 @GetMapping("/api/config)
    fun config(@PathVariable id: String): ResponseEntity<Resource> {
        val config = someService.getConfig(hotelId = id)
        val resource InputStreamResource(objectMapper.writeValueAsString(config)
                     .byteInputStream(Charsets.UTF_8))

    val responseHeaders = HttpHeaders()
    responseHeaders.add("content-disposition", 
    "attachment;filename=config.json")
    responseHeaders.add("Content-Type",MediaType.APPLICATION_OCTET_STREAM_VALUE)

    return ResponseEntity.ok()
        .headers(responseHeaders)
        .contentType(MediaType.parseMediaType("application/octet-stream"))
        .body(resource)
}

在这里您还有关于

的其他答案

Content-Disposition and Content Type

前端不应该对下载文件有影响。

答案 1 :(得分:0)

您的代码是您正在实现的API,它返回文件的内容。获取内容后,应从客户端下载文件,方法是生成一个新文件。例如,使用HttpClient库,您将获得以下代码:

CloseableHttpClient client;
HttpGet request;
HttpResponse response;
HttpEntity entity;

try {
    client = HttpClientBuilder.create().build();
    request = new HttpGet(URI);
    response = client.execute(request);
    entity = response.getEntity();  

    // The file not found, or is not available
    if(response.getStatusLine().getStatusCode() == 404) {
        throw new CustomException("The URI is not valid");
    } else {
        InputStream is = entity.getContent();
        try (FileOutputStream fos = new FileOutputStream(new File(newFilePath))) {
            int inByte;
            while((inByte = is.read()) != -1) {
                fos.write(inByte);
            }
        }
        is.close();
        client.close();
    }
} catch(IOException  e) {
    e.printStackTrace();
}

如果您希望在调用URL时直接下载文件,则必须提供文件名的完整路径:http://yourhost/yourfile.txt,并且该文件当然应该在服务器上可用。该URL的后面只是一个href HTML标记,它将指向您的文件。在您的API中,您的URL看起来像这样:@Path("/{loginId}/{file}"),其中{file}代表您要下载的文件。

相关问题