REST POST端点以下载csv文件

时间:2017-06-20 07:27:27

标签: java spring rest csv

我正在尝试下面的代码来下载带有POST REST端点的csv文件。

parse

这项工作毫无例外。但是这并没有下载任何文件。一旦调用此休息端点,如何下载.csv文件。

EDITED

@ApiOperation(value = "export",
        notes = "Export Report as a CSV")
@ApiResponses(value = {
        @ApiResponse(code = 400, message = "Bad Request"),
        @ApiResponse(code = 404, message = "Not Found"),
        @ApiResponse(code = 500, message = "Internal Server Error") })
@RequestMapping(method = RequestMethod.POST, value = "/export")
public ResponseEntity export( @RequestBody SearchCriteria criteria )
{

    SimpleDateFormat sdf = new SimpleDateFormat( "yyyyMMddHHmm" );
    SAStatsManager saStatsManager = new SAStatsManager();
    InputStreamResource inputStreamResource;
    InputStream inputStream;
    byte[] byteArray = new byte[0];
    HttpHeaders httpHeaders = new HttpHeaders();

    try
    {
        inputStreamResource = saStatsManager.export( criteria );

        if ( inputStreamResource == null )
        {
            return new ResponseEntity( "Error in exporting report!!! ", HttpStatus.OK );
        }
        httpHeaders.set( HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + REPORT_NAME+ criteria.getProductCombination() + "_" + sdf.format( new Date() ) + ".csv" );

        //convert inputStream to bytes
        inputStream = inputStreamResource.getInputStream();
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        int nRead;
        byte[] data = new byte[1024];

        while ( ( nRead = inputStream.read( data, 0, data.length ) ) != -1 )
        {
            buffer.write( data, 0, nRead );
        }

        buffer.flush();
        byteArray = buffer.toByteArray();

        httpHeaders.setContentLength( byteArray.length );
    }
    catch ( IOException e )
    {
        e.printStackTrace();
    }

    return new ResponseEntity( byteArray, httpHeaders, HttpStatus.OK );

}

非常感谢任何建议。

谢谢你

1 个答案:

答案 0 :(得分:0)

如果您正在获取URL,请尝试传递该URL以从中获取文件对象

FileUtils.copyURLToFile(URL, File);

希望它能奏效。