【问题标题】:How can I get the form name with a POST request using the multiparty package?如何使用多方包通过 POST 请求获取表单名称?
【发布时间】:2014-04-11 01:08:02
【问题描述】:

这是我目前所拥有的。这是表格(根据cybersam的回答更新)

<form method="POST" action="/view" enctype="multipart/form-data">
  <input type="image" src="/images/094_max.jpg" name="bigImage" width="300"/>
  <input type="hidden" name="file_name" value="{ source: 'test_image.jpg',
_id: 53471acd4fe44ddf04a3f752,
__v: 0,
score: 0 }"/>
</form>

这是“/view”路线

app.post('/view', vote_and_view); 

这里是路由中引用的vote_and视图函数

function vote_and_view(req,res){
  var form = new multiparty.Form();
  form.parse(req, function(err,fields){
    if(err) console.error(err)    
    console.log(fields["file_name"][0])});
  res.render('viewImage');
}

我正在尝试使用这个:https://github.com/andrewrk/node-multiparty。现在它返回一个类似

的对象
{ source: '094_max.jpg',
  _id: 53470d4b9a2a82755d911f28,
  __v: 0,
  score: 0 }

当我尝试调用 object.source 或 object['source'] 时,它返回未定义。然而对象本身被返回了?为什么会发生这种情况?如何获得此来源?

附:当我看到 _id: 53470d4b9a2a82755d911f28 时,它让我认为由于末尾的 f 而导致该整数有问题。除了我不确定如何将它转换为字符串,因为它是由我的模板从 mongodb 生成的。

【问题讨论】:

    标签: javascript forms node.js post


    【解决方案1】:

    多方包状态的 README.md,就在开头:

    解析内容类型为multipart/form-data的http请求,也称为 作为文件上传。

    因此,您要么需要使用支持application/x-www-form-urlencoded 内容的不同包,要么需要发送multipart/form-data 内容。

    下面是如何执行后者的示例,来自 HTML 规范:

      <FORM action="http://server.com/cgi/handle"
           enctype="multipart/form-data"
           method="post">
       <P>
       What is your name? <INPUT type="text" name="submit-name"><BR>
       What files are you sending? <INPUT type="file" name="files"><BR>
       <INPUT type="submit" value="Send"> <INPUT type="reset">
     </FORM>
    

    【讨论】:

    • 您对 multipart/form-data 的看法是正确的。检查我更新的问题。我现在可以正确返回对象,但无法从中提取有用信息
    【解决方案2】:

    好的,所以我要做的就是更改我的模板,以便表单输出如下所示:

    <form method="POST" action="/view" enctype="multipart/form-data">
      <input type="image" src="/images/094_max.jpg" name="bigImage" width="300"/>
      <input type="hidden" name="file_name" value="test_image.jpg"/>
    </form>
    

    您可以看到隐藏字段上的值已被简化,因此它只是文件名。这意味着返回的字段对象被简化为

    { 'bigImage.x': [ '0' ],
      'bigImage.y': [ '71' ],
      file_name: [ 'test_image.jpg' ] }
    

    因此获取 fields['file_name'][0] 返回 'test_image.jpg' 这是我想要发生的。

    问题是我猜想 mongodb 以一种奇怪的 BSON 形式从数据库返回对象。这意味着您不能使用 JSON.parse 将其从字符串格式更改为对象格式,因为它看起来像 {source:"test_image.jpg"} 而不是 {"source":"test_image.jpg"}。所以我改变了格式,这样我基本上就不需要处理这方面的问题了。对不起,如果这解释得不好。如果我需要澄清,请在 cmets 中告诉我,我很乐意这样做。

    【讨论】:

      猜你喜欢
      • 2016-08-27
      • 2017-10-27
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-24
      • 1970-01-01
      相关资源
      最近更新 更多