【问题标题】:Image is not uploading using request.post getting undefined value图片未使用 request.post 上传获取未定义的值
【发布时间】:2020-07-09 15:00:48
【问题描述】:
const formData = req.file('image')

const options = {
      url: 'myurl'',
      method: 'POST',
      formData : formData
}

request.post(options, async function(err,result,body){
    if(err)
    {
      res.json({
               success: false, 
               message: "There are some error occured in file upload"
              });
    }
    else
    {
      res.json({success: true});
    }
});

我正在尝试使用 request.post 上传图片,但它不允许我上传图片请指导如何修复它

请指导

编辑1:

  1. 我使用 ejs 作为前端。
  2. 尝试将上传的图片从一台服务器 (example1.com) 发送到另一台服务器 (example2.com)。
  3. Server1(example1.com) 由sails.js 提供支持。

谢谢

【问题讨论】:

  • 你需要传递 "Content-Type": "multipart/form-data" 作为标题。 stackoverflow.com/questions/49053193/… 这篇文章会有所帮助。另外请求 npm 包已弃用,请改用 axios。
  • 我检查了 Ivan 回答他使用了 { "image" : fs.createReadStream("./images/scr1.png ") 但我们想上传如何传递请求的文件?
  • 我先来一张清晰的图。 1)您是使用“ejs”作为前端还是其他一些框架,如“react”。 2)您正在使用 fs 模块,所以看起来上面的代码是在后端(sails.js)中编写的。 3) 如果是,您在哪里要求邮寄电话。您是否将图像从一个后端源(example1.com)发送到另一个后端源(example2.com)?
  • 是的,这里正在使用sails js,并且ejs 是的,我们正在使用microservervice 将一个后端发送到另一个后端

标签: node.js express sails.js


【解决方案1】:
  1. 在您的 ejs 表单中使用 enctype='multipart/form-data'。

  2. 由于您使用 microservervice 将该图像从一个后端 (example1.com) 发送到另一个后端 (example2.com),因此首先将该图像保存在您的第一个后端 (example1.com) 中

  3. 然后将该图像路径(example1.com/images/img1.jpg)传递给发布请求。例如

    postdata = { imageurl: 'example1.com/images/img1.jpg', 图像大小:'1200', }

  4. 只有example1.com可以访问你本地的图片路径(例如:c://temp/img1.jpg)。因此,您应该将该图像上传到您的服务器 1(example1.com)

  5. 或者将图像转换为 blob 类型并发送。这样就不需要将图片保存在 server1(example1.com) 中。

【讨论】:

  • 不能将目录保存到其他服务器吗?
  • 可以将图片转成blob类型
猜你喜欢
  • 1970-01-01
  • 2019-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-28
相关资源
最近更新 更多