Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何使用multer和react?_Node.js_Reactjs_Multer - Fatal编程技术网

Node.js 如何使用multer和react?

Node.js 如何使用multer和react?,node.js,reactjs,multer,Node.js,Reactjs,Multer,我正在用Node.js和React构建一个web应用程序,并尝试在后端存储一些文件。 由于某些原因,我无法访问我的请求路径,尽管我配置了所有的multer策略 const multer = require('multer') const config = require('config') const auth = require('../../middleware/auth') const {check , validationResult } = require('express-valid

我正在用Node.js和React构建一个web应用程序,并尝试在后端存储一些文件。 由于某些原因,我无法访问我的请求路径,尽管我配置了所有的multer策略

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);
}
我的路线:

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.....}
我的反应形式是:

 <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>

onChange(e)}/>
图像不能大于5MB,并且只能是JPG\JPEG\PNG类型

请问,我做错了什么?

看看这些例子。他们将帮助您:

多路存储:

//设置存储
var storage=multer.diskStorage({
目标:功能(请求、文件、cb){
cb(空,“上载”)
},
文件名:函数(请求、文件、cb){
cb(null,file.fieldname+'-'+Date.now())
}
})
var upload=multer({storage:storage})
处理文件上载:

app.post('/uploadfile',upload.single('myFile'),(req,res,next)=>{
const file=req.file
如果(!文件){
const error=新错误('请上载文件')
error.httpStatusCode=400
返回下一个(错误)
}
res.send(文件)
})

Node.js:

const path=require(“路径”);
const multer=要求(“multer”);
const storage=multer.diskStorage({
目的地:“./public/uploads/”,
文件名:函数(请求、文件、cb){
cb(null,“IMAGE-”+Date.now()+path.extname(file.originalname));
}
});
const upload=multer({
存储:存储,
限制:{文件大小:1000000},
}).单一(“myImage”);
const router=express.router();
router.post(“/upload”{
上传(请求、恢复、(错误)=>{
日志(“请求---”,请求主体);
console.log(“请求文件----”,req.file);//这里是文件。
/*现在去你想去的地方*/
如果(!err)
return res.send(200.end();
});
};);

我在后端应用程序中使用了multer,这就是我配置它的方式,它工作正常,并将所需文件存储在服务器文件目录中

首先,安装multer

 npm i multer --save
其次,在required.js文件的顶部初始化它

const multer = require("multer");
现在,配置存储(存储位置和文件名)

Init multer函数,(配置自己的文件大小)

如果要一次上载多个文件,请使用数组,10是文件数,您可以根据需要修改它

 const upload = multer({
      storage: storage,
      limits: { fileSize: 10000000000 },
    }).array("image", 10);
//使用。单个(“图像”);如果你想上传一个文件。 //image是从前端随文件发送的名称/密钥

如果您使用的是数组,那么可以创建一个存储文件的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);
    });
  }
对于单个文件,它看起来就这么简单

 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);
        }
      }
    });
  }

很好很漂亮的解释
 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);
        }
      }
    });
  }