3

Hi I need to upload file in react using class component as it is legacy application. I need this file in UI only so I dont want to save it into database. I have to save in the public folder also under public folder I need to give fucntionality to user to give file and folder name.

What changes I need to do in below code. Below code is perfectly working. Only thing is I need to upload file to folder and need to manaully enter file and folder name.

import axios from 'axios';
import React, { Component } from 'react';
class FileUpload extends Component {
  state = {
    selectedFile: null,
  };

  onFileChange = (event) => {
    this.setState({ selectedFile: event.target.files[0] });
  };

  onFileUpload = () => {
    const formData = new FormData();
    formData.append(
      'myFile',
      this.state.selectedFile,
      this.state.selectedFile.name
    );

    console.log(this.state.selectedFile);
    axios.post('api/uploadfile', formData);  //I need to change this line
  };

  fileData = () => {
    if (this.state.selectedFile) {
      return (
        <div>
          <h2>File Details:</h2>
          <p>File Name: {this.state.selectedFile.name}</p>
          <p>File Type: {this.state.selectedFile.type}</p>
          <p>
            Last Modified:{' '}
            {this.state.selectedFile.lastModifiedDate.toDateString()}
          </p>
        </div>
      );
    } else {
      return (
        <div>
          <br />
          <h4>Choose before Pressing the Upload button</h4>
        </div>
      );
    }
  };

  render() {
    return (
      <div>
        <h1>Plese select the translation file</h1>
        <div>
          <input type="file" onChange={this.onFileChange} />
          <button onClick={this.onFileUpload}>Upload!</button>
        </div>
        {this.fileData()}
      </div>
    );
  }
}

export default FileUpload;

Edit 1:-

enter image description here

Edit 2:-

app.listen(80, () => console.log('Listening on port 80'));
 axios.post('http://localhost:80/api/uploadfile', formData, {

Error enter image description here

1 Answer 1

2

If you save file to the public folder it will not available to the front end until you build the react project (react-scripts build). Instead of that, you can be save it directly to build folder. But next time you build the project uploaded files are gone. You can decide what to do there.

Going back to your question,

You can achieve it using running a simple server which servers fronted build files and that handles some HTTP requests.

  1. Install express (server) and multer(to handle file uplaod).
npm i express multer
  1. In the root level of your react project create another folder called server. Within that create a file called index.js and add following code.
const express = require("express");
const app = express();
const multer  = require('multer')

// setup multer for file upload
var storage = multer.diskStorage(
    {
        destination: './build',
        filename: function (req, file, cb ) {
            cb( null, file.originalname);
        }
    }
);

const upload = multer({ storage: storage } )

app.use(express.json());
// serving front end build files
app.use(express.static(__dirname + "/../build"));

// route for file upload
app.post("/api/uploadfile", upload.single('myFile'), (req, res, next) => {
    console.log(req.file.originalname + " file successfully uploaded !!");
    res.sendStatus(200);
});

app.listen(3000, () => console.log("Listening on port 3000"));

  1. To start the above server change the start command in scripts sections in package.json file. It will build the project and start running the server.
"scripts": {
    "start": "npm run build && node ./server",
    ...
    ...
}
  1. Your file upload handler need to have content type as multipart/form-data
  onFileUpload = () => {
    const formData = new FormData();
    formData.append("myFile", this.state.selectedFile);

    console.log(this.state.selectedFile);
    axios.post("http://localhost:3000/api/uploadfile", formData, {
      headers: {
        "content-type": "multipart/form-data",
      },
    }); //I need to change this line
  };

Now run npm start and try uploading a file. It will appear in build folder. You might change it as per your needs.

Sign up to request clarification or add additional context in comments.

23 Comments

@Niharika S, check this out !!
Thank you Amila. I am going through the same.
check the build folder file should be there if it's working fine. Otherwise, what's the error you get.
did you change the port to 80 in the server/index.js? then change the request to axios.post("http://localhost:80/api/uploadfile"
I'm curious why it's not working. I guess you need to exit yarn start and rerun. hot relaoding does not work with the current command
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.