我正在尝试使用Axios从Firebase获取上传的照片,并将其转换为File()对象。我将此照片上传到了我应用的其他部分,并在注册中保存了网址。现在,我正在尝试使用url从存储中取回文件。问题是,它必须是File()对象。我知道如何使用url仅显示图像,但这不是目标。

这是我的要求:

fileFromURL(url, filename) {
  const imageFile = new File([''], 'filename');
  const config = {
    headers: {
      'Content-Type': imageFile.type,
    },
  };
  this.$axios.get(url, config)
    .then((response) => {
      // Here I am trying to transform the response to an File() object.

      const byteString = btoa(response.data);
      const ab = new ArrayBuffer(byteString.length);
      const ia = new Uint8Array(ab);
      for (let i = 0; i < byteString.length; i += 1) {
        ia[i] = byteString.charCodeAt(i);
      }
      const blob = new Blob([ia], { type: 'image/jpeg' });
      const file = new File([blob], filename);
    })
    .catch(() => {
      this.$q.notify({
        color: 'negative',
        position: 'top',
        message: 'Loading failed',
        icon: 'report_problem',
      });
    });
},


这些是响应头:

accept-ranges: bytes
access-control-expose-headers: Content-Length, Date, Server, Transfer-Encoding, X-GUploader-UploadID, X-Google-Trace
alt-svc: quic=":443"; ma=2592000; v="44,43,39"
cache-control: private, max-age=0
content-disposition: inline; filename*=utf-8''avatar.jpg
content-length: 1740563
content-type: image/jpeg
date: Mon, 04 Mar 2019 16:43:31 GMT
expires: Mon, 04 Mar 2019 16:43:31 GMT
last-modified: Wed, 27 Feb 2019 17:27:52 GMT
server: UploadServer
status: 200


这是响应的一部分:

{data: "�PNG
↵↵
IHDR�x�� IDATx���w�%E�…���������������������������� �(�%�5IIEND�B`�", status: 200, statusText: "", headers: {…}, config: {…}, …}
config: {adapter: ƒ, transformRequest: {…}, transformResponse: {…}, timeout: 0, xsrfCookieName: "XSRF-TOKEN", …}
data: "�PNG
↵↵
IHDR�x�� IDATx���w�%E�"
headers: {date: "Mon, 04 Mar 2019 16:43:31 GMT", x-guploader-uploadid: "AEnB2UqVnwrANAK9hLdD6vQZA_HAIIzgmMz1EA5foN16jLnfuBcNSB0TIFr4C59I3cA4CRhnN2UloR5tdBK4UQ5IDihbpelJRQ", content-length: "16965", last-modified: "Wed, 27 Feb 2019 17:27:32 GMT", server: "UploadServer", …}
request: XMLHttpRequest {onreadystatechange: ƒ, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
status: 200
statusText: ""
__proto__: Object


如您所见,数据中填充了一个长字符串(16246个字符)。

那么如何将其更改为File()对象?

最佳答案

您可以将axios配置为直接将响应作为Blob返回,因此您不必自己使用以下方法进行转换:

responseType: 'blob'

fileFromURL(url, filename) {
  // *removed quotes from filename, typo I guess?
  const imageFile = new File([''], filename);
  const config = {
    // *removed headers as we don't know the file type anyway, I guess?
    responseType: 'blob'
  };
  this.$axios.get(url, config)
    .then((response) => {
      const file = new File([response.data], filename);
  });
}


演示:
javascript - 通过axios和Firebase获取JS file()-LMLPHP

10-05 23:24
查看更多