Convert URL to File or Blob for FileReader.readAsDataURL

后端 未结 8 869
情话喂你
情话喂你 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');
    

提交回复
热议问题