简体   繁体   中英

Using fs and aws-sdk in React

I am having trouble in loading a file from HTML to AWS s3. I have tested this with node.js running this script manually, with hardcoded values, it works. Though I am having trouble to implement this in REACT as having this error:

TypeError: fs__WEBPACK_IMPORTED_MODULE_0___default.a.readFileSync is not a function

My Code is simple I believe:

The HTML is :

 <div className="single-file-input">
            <input
              type="file"
              id="user_image"
              name="user_image"
              onChange={this.handleFiles}
            />
            <div>
              Upload a picture<i className="fa fa-upload"></i>
            </div>
          </div>

Then the js function is as per below:

handleFiles = (e) => {
uploadFile(e.target.files);

};

I am importing this function from a utils file import { uploadFile } from "../../../utils/upload"; , which looks like:

import fs from "fs";
import AWS from "aws-sdk";

/*const fs = require("fs");
const AWS = require("aws-sdk");*/

//The Below Three are defined, not adding them here of course. 
const ID = "";
const SECRET = "";
const BUCKET_NAME = "";

const s3 = new AWS.S3({
  accessKeyId: ID,
  secretAccessKey: SECRET,
  Bucket: BUCKET_NAME,
  CreateBucketConfiguration: {
    // Set your region here
    LocationConstraint: "eu-west-1",
  },
});

export const uploadFile = (fileName) => {
  // Read content from the file
  const fileContent = fs.readFileSync(fileName[0].name);

  // Setting up S3 upload parameters
  const params = {
    Bucket: BUCKET_NAME,
    Key: "TESTFILE.jpg", // File name you want to save as in S3
    Body: fileContent,
  };

  // Uploading files to the bucket
  s3.upload(params, function (err, data) {
    if (err) {
      throw err;
    }
    //Data location is used in order to get the data location in AWS S3
    console.log(`File uploaded successfully. ${data.Location}`);
  });
};

Do I need to use API, or what am I not understanding in the flow, I thought since the script works as a standalone, it should work as well here, but it doesn't.

What am I missing?

Ps Maybe someone will have a use of this code as well :)

'fs' is a NodeJS core module and cannot be used in React. React is run in browsers and they don't have direct API for accessing filesystems, unlike Node.

For React you're probably going to have more success by using react-aws-s3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM