【问题标题】:Using multer with superagent for uploading files from react使用 multer 和 superagent 从 react 上传文件
【发布时间】:2018-02-28 04:11:07
【问题描述】:

我是第一次使用 multer,遇到了一些麻烦。

我想从带有 superagent lib 的 react 客户端将图像文件上传到我的服务器上。

req.file 数据始终未定义,这是我的代码:

服务器端:

const upload = multer({ 
    dest: 'uploads/' })
app.post('/uploadprofile', upload.single('profil'), (req, res) => {
        console.log(req.file);
        console.log(req.files);
        console.log(req.body);
        res.status(200).end()
})

还有我的客户端:

onUploadFile(e) {
        console.log(e.target.files[0])
        this.setState({
            img: e.target.files[0]
        }, () => {
            agent
            .post("http://localhost:3100/uploadprofile")
            .attach('profil', this.state.img, this.state.img.name)
            .set("Content-Type", "")
            .end((err, res) => {
                console.log(err)
                console.log(res)
                console.log("send")
         })
        })
    }


render() {
return (
    <input id="file" type="file" accept="image/*" name="profil" className="inputButton" onChange={this.onUploadFile}/>
)
}

在我的超级代理请求中,我必须覆盖内容类型,否则会发送 json 数据。

req.file 在我的后端仍未定义。

感谢您的帮助!

【问题讨论】:

  • 你有没有想过这个问题?我现在也有同样的问题。

标签: javascript file express multer superagent


【解决方案1】:

问题出在您的超级代理调用上,请查看此页面: https://visionmedia.github.io/superagent/#multipart-requests

据此:

当你使用 .field() 或 .attach() 时,你不能使用 .send() 并且你不能设置 Content-Type(将为你设置正确的类型)。

所以你需要删除.set("Content-Type", ""),然后做这样的事情:

      await superagent
        .post(url)
        .withCredentials()
        .accept('application/json')
        .field('lets_try', 'ok!')                 // this would come from a form field
        .attach('staff', event.target.files[0]);  // this is your file

在服务器端,一旦你得到你的(单个)文件,你仍然需要将它的缓冲区转换为字符串,如果你需要一些文本:

  console.log(`Uploaded req.body=${JSON.stringify(req.body)}`);
  console.log(`         req.file=${JSON.stringify(req.file, null, 2)}`);
  console.log(`req.file=${req.file.buffer.toString()}`);

你会得到:

Uploaded req.body={"lets_try": "ok!"}
         req.file={
   "fieldname": "staff",
   "originalname": "test.json",
   "encoding": "7bit",
   "mimetype": "application/json",
   "buffer": {
     "0": 10,
     "1": 98,
     "2": 111,
     "3": 98,
     "4": 10,
   },
   "size": 5,
 }
req.file=
 bob

如果你的文件内容是bob :-)

【讨论】:

    猜你喜欢
    • 2021-08-29
    • 2020-09-04
    • 1970-01-01
    • 2021-08-16
    • 2020-09-22
    • 2021-04-09
    • 2016-03-09
    • 2018-08-12
    • 2016-10-22
    相关资源
    最近更新 更多