从URL获取PDF并将其推送到客户端浏览器进行下载

Dra*_*ian 4 java http urlconnection httprequest httpurlconnection

我有安装在外部服务器上的PDF。我必须在我的Java servlet中访问它们并将它们推送到客户端浏览器。PDF应该直接下载,否则可能会打开“保存或打开”对话框。这是我在代码中尝试的方法,但是不能做很多事情。

URL url = new URL("http://www01/manuals/zseries.pdf");
ByteArrayOutputStream bais = new ByteArrayOutputStream();
InputStream in = url.openStream();

int FILE_CHUNK_SIZE = 1024 * 4;
byte[] chunk = new byte[FILE_CHUNK_SIZE]; 
int n =0;
 while ( (n = in.read(chunk)) != -1 ) {
        bais.write(chunk, 0, n);
  }
Run Code Online (Sandbox Code Playgroud)

我已经尝试了许多方法来做到这一点,但未能成功。如果您有任何好的方法,欢迎您!

Rea*_*tic 5

读取数据时,会将其存储在服务器端的程序存储器中。要将其发送到用户的浏览器,您还必须编写所有已阅读的内容。

但是,在开始编写之前,应提供一些适当的标题。

  • 通过设置mime类型来指示您正在通过PDF文件发送
  • 设置内容长度。
  • 指示该文件旨在下载而不是显示在浏览器内部。

要设置MIME类型,请使用

response.setContentType("application/pdf");
Run Code Online (Sandbox Code Playgroud)

要设置内容长度(假设它与您从URL获得的内容长度相同),请使用:

HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.connect();
if ( connection.getResponseCode() == 200 ) {
    int contentLength = connection.getContentLength();
    response.setContentLength( contentLength );
Run Code Online (Sandbox Code Playgroud)

要指示您要下载文件,请使用:

    response.setHeader( "Content-Disposition", "attachment; filename=\"zseries.pdf\"";
Run Code Online (Sandbox Code Playgroud)

(请注意将文件名更改为您希望用户在“保存”对话框中看到的名称)

最后,从刚刚打开的URLConnection获取输入流,获取servlet的响应输出流,然后开始从一个读取并向另一个写入:

    InputStream pdfSource = connection.getInputStream();
    OutputStream pdfTarget = response.getOutputStream();

    int FILE_CHUNK_SIZE = 1024 * 4;
    byte[] chunk = new byte[FILE_CHUNK_SIZE]; 
    int n =0;
    while ( (n = pdfSource.read(chunk)) != -1 ) {
        pdfTarget.write(chunk, 0, n);
    }
} // End of if
Run Code Online (Sandbox Code Playgroud)

记住要使用try / catch解决这个问题,因为这些方法大多数都会抛出throw IOException,timeout异常等,并最终关闭两个流。还记得做一些有意义的事情(例如给出错误输出),以防响应不是200。