Tracking progress of file upload in multer nodejs

Deadly 提交于 2020-02-24 04:15:27

问题


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 client , So that client gets the upload progress OR this is done internally & client can track progress on its on.

Below is the code i am using to upload file :

var multer = require('multer');
app.use(multer({dest:'./tmp',limits: {fileSize: 4*1024*1024}}).single('upload'));


router.post('/upload',function(req,res){
 console.log(req.file);
});

回答1:


Here's an answer by LinusU at the project github's page (he suggests using progress-stream):

Pipe req to that one and give it to multer.

    var p = progress()
    var upload = multer().single('file')

    req.pipe(p)
    p.headers = req.headers

    p.on('progress', _)
    upload(p, res, _)



回答2:


React Frontend

const formData = new FormData();
formData.append('myImage', this.state.imageData);
const config = {
    onUploadProgress: progressEvent => console.log(progressEvent.loaded), // TO SHOW UPLOAD STATUS
    headers: {
        'content-type': 'multipart/form-data'
    }
};
axios.post("/api/api/save-media", formData, config)
    .then((response) => {
        // do whatever you want
    }).catch((error) => {
        console.log(error)
    });



回答3:


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 = (loadedInMB / totalInMB) * 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 (
    <div>
      <form onSubmit={e => onSubmit(e)} id="demo">
        <input type="file" name="avatar" id="avatar" />
        <input type="submit" value="Submit" />
      </form>
    {showProgressBar ? (
        <>
          <div className="text-center">
            {parseInt(uploadPercentage) !== 100
              ? `Upload percentage - ${uploadPercentage}`
              : "File successfully uploaded"}
          </div>
          <Progress
            animated={parseInt(uploadPercentage) !== 100}
            color="success"
            value={uploadPercentage}
          />
        </>
      ) : null}
    </div>
  );
};

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;



来源:https://stackoverflow.com/questions/35288625/tracking-progress-of-file-upload-in-multer-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!