Home > other >  File upload to custom folder in react
File upload to custom folder in react

Time:01-05

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

CodePudding user response:

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.

  •  Tags:  
  • Related