spring-mvcshippo

DownLoad Shippo label through controller


After filling necessary package info, I manage to create a responsed Transaction object through goShippo API call: Transaction.create(Map, apiKey). Form the responsed Transaction object, I can get the shipping label as a Url: transaction.getObjectId().

The problem that I have is how can I enable my client to download the shipping label.

My current code is:

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());

The error that I have is that the file is not found, but when I pass the fileName on browser, I can see the shipping label.


Solution

  • The documentation says:

    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.

    So you need to create a URL object and from it you can get the inputStream.

    It looks like this:

    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());