【问题标题】:React: How to avoid performance problem when uploading images to CloudinaryReact:上传图片到 Cloudinary 时如何避免性能问题
【发布时间】:2021-03-23 23:01:20
【问题描述】:

我编写了一个有效的代码,但它不是杰作。它有巨大的性能问题。我该如何处理?

问题

我的组件性能有问题:

  1. 发送多张图片很慢,当我发送5张图片时,大约需要1-2分钟。
  2. 如何确保照片仅在提交期间上传到 Cloudinary? 因为,例如,当用户选择照片 A,然后环顾四周并选择照片 B 时,照片 A 和 B 会上传到云端。

问题

在将文件传输到 Cloudinary 时禁用添加相册的按钮是个好主意吗?

请帮我解决这两个问题,我想确保应用程序顺利运行。非常感谢。

const AddAlbum = () => {

  const [fileUrl, setFileUrl] = useState();

  // MultipleFiles
  const [multipleFileUrl, setMultipleFileUrl] = useState([]);
 
  // cloudnary upload api endpoint
  const api_cloudinary =
    "https://api.cloudinary.com/v1_1/cloudinary_name/image/upload";

  
  // file upload
  const handleSingleFileUpload = async (files) => {
  

    const formData = new FormData();
    formData.append("file", files[0]);
    formData.append("upload_preset", "preset_number");
    // send cloudinary image and presets info
    const res = await fetch(api_cloudinary, {
      method: "POST",
      body: formData,
    });

    const file = await res.json();
    console.log(file);
    const fileUrl = await file.eager[0].url;
    setFileUrl(fileUrl);
  };
  console.log(fileUrl);
  // upload many files cloudnary
  // For now max amount of files is 20
  const handleMultipleFileUpload = async (files, amount) => {
    const formData = new FormData();

    for (let i = 0; i <= files.length; i++) {
      let file = files[i];
      formData.append("file", file);
      formData.append("upload_preset", ""preset_number"");

      const res = await fetch(api_cloudinary, {
        method: "POST",
        body: formData,
      });

      const cloudinaryFiles = await res.json();
      console.log(cloudinaryFiles);
      setMultipleFileUrl(cloudinaryFiles);
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    console.log(
      `
      Album name:${albumName}
      color:${color}
      Background Image: ${fileUrl}
      files:${multipleFileUrl}
      `
    );
  };
 

和表格

 return (
    <Wrapper>
    
      <form onSubmit={handleSubmit}>
       
    
        <div>
          <StyledLabel>Upload background image</StyledLabel>
          <DefaultInput
            type="file"
            onChange={(e) => handleSingleFileUpload(e.target.files)}
          />
        </div>
        <div>
          <StyledLabel>Upload background image</StyledLabel>
          <DefaultInput
            type="file"
            onChange={(e) => handleMultipleFileUpload(e.target.files)}
            multiple
          />
        </div>
       
        
        <StyledButton type="submit">Submit</StyledButton>
      </form>
    </Wrapper>
  );
};

【问题讨论】:

    标签: javascript reactjs performance react-hooks cloudinary


    【解决方案1】:

    您只需要 1 个函数即可处理 1 个或多个图像文件。您需要获取每个文件的内容并将文件的内容加载到表单数据中。示例代码使用浏览器 FileReader API 读取本地图像文件的内容。查看 repl.it 中使用 vanilla JS 的这段代码。如果有意义,您可以将其放入您的框架中。让我知道是否有问题。 https://repl.it/@rpeltz/fe-upload#script.js

      reader.addEventListener(
          "load", function () {
            const fileContents = reader.result;
    
    
    

    https://developer.mozilla.org/en-US/docs/Web/API/FileReader

    【讨论】:

      【解决方案2】:

      我建议使用为您处理此问题的库。在处理文件上传时,您需要注意许多边缘情况。

      react-uploady 例如为您执行此操作。就这么简单:

      import React from "react";
      import Uploady from "@rpldy/uploady";
      import UploadButton from "@rpldy/upload-button";
      
      const CLOUD_NAME = "<your-cloud-name>";
      const UPLOAD_PRESET = "<your-upload-preset>";
      
      const App = () => (<Uploady
          destination={{ 
              url: `https://api.cloudinary.com/v1_1/${CLOUD_NAME}/upload`,
              params: {
                  upload_preset: UPLOAD_PRESET,
              }
          }}>
          <UploadButton/>
      </Uploady>);
      

      对于您不想允许未签名上传的生产代码,我建议您查看guide

      【讨论】:

        猜你喜欢
        • 2022-01-14
        • 2019-05-07
        • 2020-09-20
        • 1970-01-01
        • 2021-04-22
        • 2022-01-12
        • 2016-04-12
        • 2022-12-16
        • 2016-09-20
        相关资源
        最近更新 更多