在泽西2中流式传输多部分

时间:2015-03-25 17:30:50

标签: java json jersey streaming multipart

我目前使用Jersey REST代码来流式传输一个效果很好的文件:

StreamingOutput stream = new StreamingOutput() {
    @Override
    public void write(OutputStream out)
    throws IOException {
        final BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(out);

        // Stream is filled with data in this method.
        restDAO.readData(bufferedOutputStream);
        bufferedOutputStream.flush();
        bufferedOutputStream.close();
    }
};

return Response.ok(body, mimeType).header("filename", getFileName()).build();

但是,我想要流式传输包含大文件和JSON的多部分文件,执行以下操作:

FormDataMultiPart multiPart = new FormDataMultiPart();
multiPart.bodyPart(jsonObject, MediaType.APPLICATION_JSON_TYPE);
String mimeType = "application/octet-stream";

StreamingOutput stream = new StreamingOutput() {
    @Override
    public void write(OutputStream out)
    throws IOException {
        final BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(out);

        // Stream is filled with data in this method.
        restDAO.readData(bufferedOutputStream);
        bufferedOutputStream.flush();
        bufferedOutputStream.close();
    }
};
multiPart.bodyPart(stream, MediaTypeUtil.stringToMediaType(mimeType));

return Response.ok(multiPart, MediaType.MULTIPART_FORM_DATA).build();

但是,上面的代码不起作用。运行时出现此错误:javax.ws.rs.BadRequestException:HTTP 400 Bad Request

是否可以以类似的方式传输multiPart?我看到的主要问题是进入multipart的文件来自流本身。

1 个答案:

答案 0 :(得分:0)

为了正确地传输多部分,我最终使用了 PipedInputStream PipedOutputStream 以及一个帖子:

PipedOutputStream pipedOutputStream = new PipedOutputStream();
PipedInputStream pipedInputStream = new PipedInputStream(pipedOutputStream);
final BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(pipedOutputStream);

FormDataMultiPart multiPart = new FormDataMultiPart();
multiPart.bodyPart(jsonObject, MediaType.APPLICATION_JSON_TYPE);
String mimeType = "application/octet-stream";

// Multipart streaming.
// Write to the PipedOutputStream in a separate thread
Runnable runnable = new Runnable() {
    public void run() {
        try {
            restDAO.readData(bufferedOutputStream);
            bufferedOutputStream.flush();
            bufferedOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
};

Thread fileThread = new Thread(runnable, "MultiPartFileStreamer");
fileThread.start();
final StreamDataBodyPart streamDataBodyPart = new StreamDataBodyPart(
    "file", pipedInputStream, data.getContentFileName(), 
    MediaUtils.stringToMediaType(mimeType));
multiPart.bodyPart(streamDataBodyPart);

return Response.ok(multiPart, MediaType.MULTIPART_FORM_DATA).build();