【问题标题】:Resize an image, before uploading to Firebase Storage using Javascript [duplicate]在使用 Javascript 上传到 Firebase 存储之前调整图像大小 [重复]
【发布时间】:2021-10-26 17:51:24
【问题描述】:

我的以下用于将图像上传到 Firebase 存储的代码工作正常。

但我想将“file1(图像)”的文件大小减小到 100px*100px。并将其上传到 Firebase 存储。

    function uploadImage() {

     const ref = firebase.storage().ref();
     const file1 = document.querySelector("#photo").files[0];
                
      
      const metadata = {
        contentType: file1.type
      };
      const task = ref.child(mydata.uid).put(file1, metadata);
      task
        .then(snapshot => snapshot.ref.getDownloadURL())
        .then(url => {
            db.collection('user').doc(mydata.docid).update({
              profilepic : url,
            });  
          const image = document.querySelector("#image")
          image.src = url;
          alert("uploaded")
        })
        .catch(console.error);
    }

请提供将调整大小的图片上传到 Firebase 存储的完整代码。

【问题讨论】:

标签: javascript reactjs firebase resize firebase-storage


【解决方案1】:

由于您的问题似乎是针对 React,有一个 npm 包可以做到这一点:React Image Resizer

按照 npm 包文档中的说明包装调整大小后,您将修改代码如下:

async function uploadImage() {

    const ref = firebase.storage().ref();
    const file1 = document.querySelector("#photo").files[0];
    const resizedImg =  await resizeFile(file1);



    const metadata = {
        contentType: file1.type
    };
    const task = ref.child(mydata.uid).putString(resizedImg, 'base64', metadata);
    task
        .then(snapshot => snapshot.ref.getDownloadURL())
        .then(url => {
            db.collection('user').doc(mydata.docid).update({
                profilepic : url,
            });
            const image = document.querySelector("#image")
            image.src = url;
            alert("uploaded")
        })
        .catch(console.error);
}

【讨论】:

  • 但它给出了一个错误 - Line 190:37: 'resizeFile' is not defined no-undef
  • @SpandanManna 您需要使用 npm 安装包,然后将调整大小包装在您自己的函数中,如此处包文档的示例 1 中所述:npmjs.com/package/react-image-file-resizer
猜你喜欢
  • 2021-11-30
  • 2021-08-19
  • 2017-04-27
  • 2016-09-30
  • 2021-11-14
  • 2018-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多