react js handling file upload

后端 未结 7 961
长发绾君心
长发绾君心 2020-12-09 11:29

I\'m new to react js. I want to upload image asynchronously with react js Suppose I have this code

var FormBox = React.createClass({
  getInitialState: funct         


        
7条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-09 12:04

    If you are planning to upload files using node and express then you have to create both server and client. The server has the api and the client is going to use that for uploading the file with axios.

    • Server part

    First, we want to put in four packages that are express, explicit-fileupload,cors and nodemon. Run the below command to install applications.

    npm i express express-fileupload cors nodemon
    

    Now open the fileupload folder in your favorite code editor and create a brand new document referred to as server.js.

    // server.js
    const express = require('express');
    const fileUpload = require('express-fileupload');
    const cors = require('cors')
    const app = express();
    // middle ware
    app.use(express.static('public')); //to access the files in public folder
    app.use(cors()); // it enables all cors requests
    app.use(fileUpload());
    // file upload api
    app.post('/upload', (req, res) => {
        if (!req.files) {
            return res.status(500).send({ msg: "file is not found" })
        }
            // accessing the file
        const myFile = req.files.file;
        //  mv() method places the file inside public directory
        myFile.mv(`${__dirname}/public/${myFile.name}`, function (err) {
            if (err) {
                console.log(err)
                return res.status(500).send({ msg: "Error occured" });
            }
            // returing the response with file path and name
            return res.send({name: myFile.name, path: `/${myFile.name}`});
        });
    })
    app.listen(4500, () => {
        console.log('server is running at port 4500');
    })
    

    use node server.js to start the server running.

    • Client

    Open the react app folder on your favorite code editor and create a brand new report known as fileupload.js within the src folder. Now upload the following code.

    // fileupload.js
    import React, { useRef, useState } from 'react';
    import axios from 'axios';
    function FileUpload() {
        const [file, setFile] = useState(''); // storing the uploaded file    
        // storing the recived file from backend
        const [data, getFile] = useState({ name: "", path: "" });    
        const [progress, setProgess] = useState(0); // progess bar
        const el = useRef(); // accesing input element
        const handleChange = (e) => {
            setProgess(0)
            const file = e.target.files[0]; // accesing file
            console.log(file);
            setFile(file); // storing file
        }
        const uploadFile = () => {
            const formData = new FormData();        
            formData.append('file', file); // appending file
            axios.post('http://localhost:4500/upload', formData, {
                onUploadProgress: (ProgressEvent) => {
                    let progress = Math.round(
                    ProgressEvent.loaded / ProgressEvent.total * 100) + '%';
                    setProgess(progress);
                }
            }).then(res => {
                console.log(res);
                getFile({ name: res.data.name,
                         path: 'http://localhost:4500' + res.data.path
                       })
            }).catch(err => console.log(err))}
        return (
            
    {progress}

    {/* displaying received video*/} {data.path &&
    ); } export default FileUpload;

    Now import the FileUpload component inside the App.js file.

    // App.js
    import React from 'react';
    import FileUpload from './fileupload';
    import './App.css';
    function App() {
      return (
        
    ); } export default App;

    Start the react app by running npm start.

    For more: React File Upload Demo

提交回复
热议问题