31

私は3台のマシンを持っています:

  1. ファイルが置かれているサーバー
  2. REST サービスが実行されているサーバー (ジャージー)
  3. 2 番目のサーバーにはアクセスできるが、1 番目のサーバーにはアクセスできないクライアント (ブラウザー)

直接 (2 番目のサーバーにファイルを保存せずに) 1 番目のサーバーからクライアントのマシンにファイルをダウンロードするにはどうすればよいですか?
2 番目のサーバーからByteArrayOutputStreamを取得して、1 番目のサーバーからファイルを取得できます。REST サービスを使用して、このストリームをさらにクライアントに渡すことはできますか?

このように動作しますか?

したがって、基本的に私が達成したいのは、データストリームのみを使用して、クライアントが第2サーバーのRESTサービスを使用して第1サーバーからファイルをダウンロードできるようにすることです(クライアントから第1サーバーへの直接アクセスがないため)。 2 番目のサーバーのシステム)。

EasyStreamライブラリで今試していること:

final FTDClient client = FTDClient.getInstance();

try {
    final InputStreamFromOutputStream <String> isOs = new InputStreamFromOutputStream <String>() {
        @Override
        public String produce(final OutputStream dataSink) throws Exception {
            return client.downloadFile2(location, Integer.valueOf(spaceId), URLDecoder.decode(filePath, "UTF-8"), dataSink);
        }
    };
    try {
        String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);

        StreamingOutput output = new StreamingOutput() {
            @Override
            public void write(OutputStream outputStream) throws IOException, WebApplicationException {
                int length;
                byte[] buffer = new byte[1024];
                while ((length = isOs.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, length);
                }
                outputStream.flush();
            }
        };
        return Response.ok(output, MediaType.APPLICATION_OCTET_STREAM)
            .header("Content-Disposition", "attachment; filename=\"" + fileName + "\"")
            .build();
    }
}

更新2

したがって、カスタム MessageBodyWriter を使用した私のコードは単純に見えます。

ByteArrayOutputStream baos = new ByteArrayOutputStream(2048) ;
client.downloadFile(location, spaceId, filePath, baos);
return Response.ok(baos).build();

しかし、大きなファイルを試してみると、同じヒープ エラーが発生します。

UPDATE3 ついにそれを機能させることができました! StreamingOutput はうまくいきました。

ありがとうございます!どうもありがとう !

4

3 に答える 3

0

これを参照してください:

@RequestMapping(value="download", method=RequestMethod.GET)
public void getDownload(HttpServletResponse response) {

// Get your file stream from wherever.
InputStream myStream = someClass.returnFile();

// Set the content type and attachment header.
response.addHeader("Content-disposition", "attachment;filename=myfilename.txt");
response.setContentType("txt/plain");

// Copy the stream to the response's output stream.
IOUtils.copy(myStream, response.getOutputStream());
response.flushBuffer();
}

詳細: https://twilblog.github.io/java/spring/rest/file/stream/2015/08/14/return-a-file-stream-from-spring-rest.html

于 2016-11-10T10:47:20.367 に答える