Tracking progress of file upload in multer nodejs

前端 未结 4 1408
野趣味
野趣味 2021-02-15 17:01

How to track progress of a file getting uploaded to NodeJs server .I am using multer in server side to upload files. ?

Do i need to send some kind of information to the

4条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-15 17:46

    working code

    REACTJS CODE (FRONT END) USING HOOKS

    upload.js or upload.jsx

    import React, { useState } from "react";
    import Axios from "axios";
    import { Progress } from "reactstrap";
    
    const Upload = () => {
      const [uploadPercentage, setUploadPercentage] = useState(0);
      const [showProgressBar, setProgressBarVisibility] = useState(false);
      const onSubmit = e => {
        e.preventDefault();
        setProgressBarVisibility(true);
        const demo = document.getElementById("demo");
        const bodyFormData = new FormData(demo);
        Axios({
          headers: {
            "Content-Type": "multipart/form-data",
          },
          method: "POST",
          data: bodyFormData,
          url: "/profile", // route name
          baseURL: "http://localhost:5000/api/upload", //local url
          onUploadProgress: progress => {
            const { total, loaded } = progress;
            const totalSizeInMB = total / 1000000;
            const loadedSizeInMB = loaded / 1000000;
            const uploadPercentage = (loadedSizeInMB / totalSizeInMB) * 100;
            setUploadPercentage(uploadPercentage.toFixed(2));
            console.log("total size in MB ==> ", totalSizeInMB);
            console.log("uploaded size in MB ==> ", loadedSizeInMB);
          },
          encType: "multipart/form-data",
        });
      };
    
    const handleFormClick = () => {
        setProgressBarVisibility(false);
        setUploadPercentage(0);
      };
    
      return (
        
    onSubmit(e)} id="demo">
    {showProgressBar ? ( <>
    {parseInt(uploadPercentage) !== 100 ? `Upload percentage - ${uploadPercentage}` : "File successfully uploaded"}
    ) : null}
    ); }; export default Upload;

    NODEJS CODE (BACKEND)

    upload.js

    const express = require("express");
    const multer = require("multer");
    const router = express.Router();
    
    var storage = multer.diskStorage({
      destination: "./uploads/",
      filename: function(req, file, cb) {
        cb(null, file.originalname);
      },
    });
    
    const upload = multer({ storage });
    
    router.post("/profile", upload.single("avatar"), function(req, res, next) {
      console.log(req.file);
      if (req.file) {
        return res.status(200).json(req.file);
      }
      return res.status(400).json({ msg: "PLEASE UPLOAD FILE" });
    });
    
    module.exports = router;
    
    

提交回复
热议问题