繁体   English   中英

如何在multer中访问FormData中的文件

[英]How to access file in FormData in multer

我正在尝试从带有fetch的反应前端上传文件到带有 multer 的 node.js 后端。 以下是我的fetch代码:

submitpost=(e)=>{
        e.preventDefault();
        var data=new FormData();
        data.append('file',this.state.shareImage)
        fetch("http://localhost:8080/post", {
             method: 'POST',
             body: data
        }).then((response) =>  {
           console.log(response.json());
        })
    }

图像位于组件的 state 中。 下面是服务器代码:

const express=require('express')
const app=express()
const bodyParser=require('body-parser')
const multer=require('multer')
const cors=require('cors')

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(express.json());
app.use(express.urlencoded());
app.use(cors());

var storage1 = multer.diskStorage({
    destination: function (req, file, cb) {

        // Uploads is the Upload_folder_name
        cb(null, "images")
    },
    filename: function (req, file, cb) {
    cb(null, file.fieldname + "-" + Date.now()+".jpg")
    }
})

const upload = multer({
    storage: storage1
})
app.post('/post',upload.single('myfile'),(req,res)=>{
    console.log(req.body);
    res.send(JSON.stringify({'status':'success'}))
})


app.listen(8080,function(error) {
    if(error) throw error
        console.log("Server created Successfully on PORT 8080")
})

当我在控制台中看到时, req.body是空的。 这就是我的input的样子:

<input type="file" 
                                accept="image/*" 
                                name="myfile"
                                id="file"
                                style={{display: 'none'}}
                                onChange={(event)=>{this.handleChange(event)}} 
                                />

下面是网络选项卡中看到的请求标头:

Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,hi;q=0.8
Connection: keep-alive
Content-Length: 135326
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryE9U4gJpcqK2hAdXC
Host: localhost:8080
Origin: http://localhost:3000
Referer: http://localhost:3000/
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site

我的问题是这是否是接收文件的正确方法。 如果是,为什么req.body是空的?

请帮我找出问题所在。

谢谢你!

该代码当前初始化multer中间件,但不使用它。 根据文档,这是您使用它的方式:

app.post("/post", upload.single("file"), (req, res) => {
  // "file" is the name of the field which contains the file

  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any
  console.log(req.file);
  console.log(req.body);
  res.send(JSON.stringify({ status: "success" }));
});

作为附加说明,express 有一个用于处理 JSON 的助手。 您可以将res.send(JSON.stringify(...))替换为res.json(...)

app.post("/post", upload.single("file"), (req, res) => {
  // "file" is the name of the field which contains the file

  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any
  console.log(req.file);
  console.log(req.body);
  res.json({ status: "success" });
});

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM