Search code examples
reactjsfile-uploadminio

minio file upload in react js


I encountered an issue with opening a file that I uploaded to a Minio Bucket. Here's the process I followed: I received the file from the user, converted it to base64, then converted it to a buffer. I successfully saved the file using the putObject API in Minio, but now I'm unable to open the file. If anyone has experience with this problem, could you please provide guidance on what steps I should take to resolve it?

//My function

 const [fileData, setFileData] = useState(); //The file selected by the user is stored in the fileData state.

 const uploadObj = () => {

    const fileBuffer = new FileReader();
    fileBuffer.readAsDataURL(fileData);

    fileBuffer.onload = function () {
      let buf = Buffer.from(fileBuffer.result, "base64"); //buffer data

      mc.putObject("BucketName", "FileName", buf, function (err, etag) {
        return console.log(err, etag); // err should be null
      });
    };
    fileBuffer.onerror = function (error) {
      console.log("Error: ", error);
    };
}

Solution

  • Finally, I found my mistake. That error is readAsDataURL. Please change it to readAsArrayBuffer and it works fine.

    more info about FileReader here

     const [fileData, setFileData] = useState(); //The file selected by the user is stored in the fileData state.
    
    
     const uploadObj = () => {
    
        const fileBuffer = new FileReader();
        fileBuffer.readAsArrayBuffer(fileData);
    
        fileBuffer.onload = async function () {
          let buf = Buffer.from(fileBuffer.result, "base64"); //buffer data
    
          await mc.putObject("hello", "FileName", buf, function (err, etag) {
            return console.log(err, etag); // err should be null
          });
        };
        fileBuffer.onerror = function (error) {
          console.log("Error: ", error);
        };
      }