简体   繁体   English

我如何使用 multer 进行反应?

[英]How can i use multer with react?

I am build a web app with Node.js and React and I am trying to store some files at my backend.我正在使用 Node.js 和 React 构建一个 web 应用程序,并且我正在尝试在我的后端存储一些文件。 For some reason i cant access to my req.path, although I configured all multer strategies.出于某种原因,尽管我配置了所有 multer 策略,但我无法访问我的 req.path。

const multer = require('multer')
const config = require('config')
const auth = require('../../middleware/auth')
const {check , validationResult } = require('express-validator');

const storage = multer.diskStorage({
    destination: function(req, file , cb){
        cb(null,'uploads/')
    },
    filename: function(req, file, cb){
        cb(null, req.user.id)
    }
});

const fileFilter = (req, file , cb) =>{
    if(file.mimetype === 'image/jpeg' || file.mimetype === 'image/jpg' || file.mimetype === 'image/png')
    cb(null,false);
    else
    cb(null,true);
}

my route:我的路线:

router.post('/' , [auth,upload.single('image'),
    [
    check('status','Status is required').not().isEmpty(),
    check('skills','Skills is required').not().isEmpty(),
    check('gender','Gender is required').not().isEmpty()
    ]],
    async (req,res) => {// cant access to req.file.....}

and my react form:和我的反应形式:

 <div className="form-group">
                   <input type="text" placeholder="Choose profile image" name="profileImage" value={image}/>
                   <input type="file" placeholder="Upload"  enctype="multipart/form-data" name="image" onChange={(e) => onChange(e)}/>
                   <small className="form-text">The image must not be bigger then 5MB and only JPG\JPEG\PNG types</small>
 </div>

Please, what am i doing wrong?请问,我做错了什么?

I have used multer in my backend application and this is how I have configured it and it works properly and stores required files in server file directory.我在我的后端应用程序中使用了 multer,这就是我配置它的方式,它可以正常工作并将所需的文件存储在服务器文件目录中。

First, installing multer一、安装multer

 npm i multer --save

Second, initialize it at the top of required.js file二、在 required.js 文件顶部初始化

const multer = require("multer");

Now, configuring storage (storage location and filename)现在,配置存储(存储位置和文件名)

  const storage = multer.diskStorage({
      destination: "./public/uploads/postimages/",
      filename: function (req, file, cb) {
        cb(
          null,
          file.fieldname + "-" + Date.now() + path.extname(file.originalname)
        );
      },
    });

Init multer function, (configure own file size) init multer function,(配置自己的文件大小)

Use array if you want to upload multiple files at once, 10 is the number of files, you can modify it as needed.如果要一次上传多个文件,请使用数组,10是文件数,您可以根据需要进行修改。

 const upload = multer({
      storage: storage,
      limits: { fileSize: 10000000000 },
    }).array("image", 10);

// Use.single("image"); // 使用.single("image"); if you want to upload a single file.如果要上传单个文件。 // image is the name/key that is sent from frontend with the file(s). // 图像是从前端与文件一起发送的名称/密钥。

If you are using array, you can create an api that stores file, which will look like this.如果你使用数组,你可以创建一个 api 来存储文件,它看起来像这样。

  try {
    let imagePath = "abc";
    let postId = req.params.postId;
    let imagesLinks = [];

    await upload(req, res, (err) => {
      if (err) {
        console.log(err);
      } else {
        if (req.files == undefined) {
          console.log("File not found.");
        } else {
          //image uploaded successfully

          req.files.map(function (file) {
            imagePath = "uploads/postimages/" + file.filename;
            imagesLinks.push(tmp);
          });
        }
      }
      res.status(201).send(imagesLinks);
    });
  }

For a single file, it looks as simple as this对于单个文件,看起来就这么简单

 try {
    let imagePath = "abc";

    upload(req, res, (err) => {
      if (err) {
        res.status(300).send(err);
        console.log(err);
      } else {
        if (req.file == undefined) {
          res.status(301).send("image upload failed.");
        } else {
          //image uploaded successfully
          imagePath = "uploads/" + req.file.filename;
          storeImageLink(res, imagePath);
        }
      }
    });
  }

Look at these examples.看看这些例子。 They will be help you:他们会帮助你:

File Upload With Multer in Node.js and Express 在 Node.js 和 Express 中使用 Multer 上传文件

Multer Storage:多用途存储:

// SET STORAGE
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads')
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now())
  }
})
 
var upload = multer({ storage: storage })

Handling File Uploads:处理文件上传:

app.post('/uploadfile', upload.single('myFile'), (req, res, next) => {
  const file = req.file
  if (!file) {
    const error = new Error('Please upload a file')
    error.httpStatusCode = 400
    return next(error)
  }
    res.send(file)
  
})

Reactjs nodejs upload image — How to upload image using reactjs and nodejs (multer) Reactjs nodejs 上传图片 — 如何使用 reactjs 和 nodejs (multer) 上传图片

Node.js: Node.js:

const path = require("path");
const multer = require("multer");

const storage = multer.diskStorage({
   destination: "./public/uploads/",
   filename: function(req, file, cb){
      cb(null,"IMAGE-" + Date.now() + path.extname(file.originalname));
   }
});

const upload = multer({
   storage: storage,
   limits:{fileSize: 1000000},
}).single("myImage");
const router = express.Router();
router.post("/upload", {
   upload(req, res, (err) => {
      console.log("Request ---", req.body);
      console.log("Request file ---", req.file);//Here you get file.
      /*Now do where ever you want to do*/
      if(!err)
         return res.send(200).end();
   });
};);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Node JS中使用multer将文件发送到api? - How can I send file to api that use multer in node js? 我如何导出multer模块 - How I can export multer module Node / React:我无法使用multer上传带有我的帖子的图像 - Node / React : I can't upload an image with my post with multer 如何使用其他字段验证来停止在Multer中上传文件? - How can I use other fields validation to stop file uploading in Multer? 如何将 Multer 与 Express.static(“public”) 和 EJS 一起用作视图引擎? - How can I use Multer with Express.static(“public”) and EJS as view engine? 如何仅对文本文件使用拖放和 multer 并将它们存储在 sqlite 数据库中 - How can I use drag and drop and multer only for text files and store them in a sqlite db 我如何使用 multer 上传视频并强制格式为 mp4 - how can i use multer to upload a video and force the format to be mp4 使用 React.js、Node.js 和 Multer,我如何在服务器上控制台日志“req.file”? - Using React.js, Node.js and Multer, how can I console log 'req.file' on the server? 当 multer 是 localhost 时,如何将文件从 multer 发送到托管在服务器上的网站文件夹 - How can i send a file from multer to my website folder which is hosted on a server while multer is localhost 如何使用 multer 将文件上传到 S3 而无需 multer 在本地存储文件副本? - How can I upload files to S3 using multer without having multer store a copy of the files locally?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM