通过控制器下载七宝标签

DownLoad Shippo label through controller

填写必要的包裹信息后,我设法通过 goShippo API 调用创建了一个响应的事务对象:Transaction.create(Map, apiKey)。从响应的交易对象中,我可以获得运输标签作为 Url: transaction.getObjectId()。

我遇到的问题是如何让我的客户下载发货标签。

我当前的代码是:

fileName= "https://shippo-delivery-east.s3.amazonaws.com/b1b0e6af.pdf?xxxxxx";

File file = new File(fileName);
String mineType = URLConnection.guessContentTypeFromName(file.getName());
    if(mineType == null) {
        System.out.println("mineType is not detectable");
        mineType = "application/octet-stream";
    }

    response.setContentType(mineType);
    response.setHeader("Content-Disposition"
            , String.format("inline; filename=\"" + file.getName() +"\""));


    response.setContentLength((int)file.length());

    InputStream inputStream = new BufferedInputStream(new FileInputStream(file));

    FileCopyUtils.copy(inputStream, response.getOutputStream());

我遇到的错误是找不到文件,但是当我在浏览器上传递文件名时,我可以看到运输标签。

documentation 说:

After you've successfully created a URL, you can call the URL's openStream() method to get a stream from which you can read the contents of the URL. The openStream() method returns a java.io.InputStream object, so reading from a URL is as easy as reading from an input stream.

因此您需要创建一个 URL 对象并从中获取 inputStream.

看起来像这样:

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;

String fileName= "https://shippo-delivery-east.s3.amazonaws.com/b1b0e6af.pdf?xxxxxx";

URL urlToLabel = new URL(fileName);

InputStream inputStream = new BufferedInputStream(urlToLabel.openStream());