Convert URL to File or Blob for FileReader.readAsDataURL

后端 未结 8 807
情话喂你
情话喂你 2020-11-27 13:57

Reference: FileReader.readAsDataURL

Considering the following example:

function previewFile(file) {

  var reader  = new FileReader();

  reader.onlo         


        
相关标签:
8条回答
  • 2020-11-27 14:59

    The suggested edit queue is full for @tibor-udvari's excellent fetch answer, so I'll post my suggested edits as a new answer.

    This function gets the content type from the header if returned, otherwise falls back on a settable default type.

    async function getFileFromUrl(url, name, defaultType = 'image/jpeg'){
      const response = await fetch(url);
      const data = await response.blob();
      return new File([data], name, {
        type: response.headers.get('content-type') || defaultType,
      });
    }
    
    // `await` can only be used in an async body, but showing it here for simplicity.
    const file = await getFileFromUrl('https://example.com/image.jpg', 'example.jpg');
    
    0 讨论(0)
  • 2020-11-27 15:01

    Expanding on Felix Turner s response, here is how I would use this approach with the fetch API.

    async function createFile(){
      let response = await fetch('http://127.0.0.1:8080/test.jpg');
      let data = await response.blob();
      let metadata = {
        type: 'image/jpeg'
      };
      let file = new File([data], "test.jpg", metadata);
      // ... do something with the file or return it
    }
    createFile();
    
    0 讨论(0)
提交回复
热议问题