简体   繁体   中英

Download the image returned by an API

I am working with the sportradar api. The api call that I am making, returns a png image. Till now I have done this.

    const apiCall = (url) => {
        return axios.get(url).then((data) => {
            if(data){
                return Promise.resolve(data);
            }
            else{
                return Promise.reject();
            }
        });
    }

    //all data in data.assetlist
    for(let i=0; i<data.assetlist.length; i++){
        let imageLink = data.assetlist[i].links[12].href;
        let url = `https://api.sportradar.us/nfl-images-p3/ap_premium${imageLink}?api_key=${api_key}`;
        apiCall(url).then((data) => {
            console.log(data);
            let blob = new Blob(data, {type: "image/png"}); // didn't compile with this line

        });
   }

The above code is working fine and is returning the data. But the data are weird character, which if I am understanding it correctly, is because of the fact that image is a blob type and I am getting a stream of data.

I took reference from here and wrote this line

let blob = new Blob(data, {type: "image/png"});

I didn't try this, because I am afraid that the data is so big that it might crash my system (old laptop). If I am doing this right, I wanna know, how to save this blob file into my system as a png file and if not then I wanna know how can i convert this stream of data into an image and can download and save it in a local directory.

If the image you get is already a blob you can download it using this library : https://github.com/eligrey/FileSaver.js

let FileSaver = require('file-saver');
FileSaver.saveAs(blob, "my_image.png");

I think you shouldn't be so worried about the size and just go for it.

After a lot of research, I found this solution and it worked.

apiCall(url).then((response) => {
        response.data.pipe(fs.createWriteStream('test.jpg'));
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM