简体   繁体   中英

How to retrieve an Image from img tag with remote url and create File object from it

Steps:

I have a remote image url.

I generated the img tag from it.

Now I want to read this img tag and convert it into a File object so that I can send it to server for upload.

Method 1 Tried: I have already tried the fetch method and directly tried to fetch image data from remote url.

Method 2 Tried:

clicked = () => {
const img = document.getElementById('someId');

const options = {
  method: 'get',
  headers: {
    'Access-Control-Request-Headers': '*',
    'Access-Control-Request-Method': '*',
  },
  mode: 'cors',
};

fetch(img.src, options)
  .then(res => res.blob())
  .then((blob) => {
    const file = new File([blob], 'dot.png', blob);
    console.log(file);
  });
}

Expected output is File object.

I am using axios here but the principal should be the same:

const res = await axios.get(`/api/image/${imageId}`, {
responseType: 'arraybuffer'
});
const imgFile = new Blob([res.data]);
const imgUrl = URL.createObjectURL(imgFile);

Ignore the response type.

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