将带有元数据(`multipart/form Data`)的文件上载到ColdFusion 11 REST服务

将带有元数据(`multipart/form Data`)的文件上载到ColdFusion 11 REST服务,rest,file-upload,coldfusion,coldfusion-11,Rest,File Upload,Coldfusion,Coldfusion 11,如何在ColdFusion 11 REST服务中访问通过文件上传(使用enctype=“multipart/form data”)发送的元数据(表单数据) 模拟一个简单的服务: component restpath = "test" rest = true { remote void function upload( required numeric id restargsource = "Path", required any docum

如何在ColdFusion 11 REST服务中访问通过文件上传(使用
enctype=“multipart/form data”
)发送的元数据(表单数据)

模拟一个简单的服务:

component
  restpath = "test"
  rest     = true
{
  remote void function upload(
    required numeric id       restargsource = "Path",
    required any     document restargsource = "Form",
    required string  title    restargsource = "Form"
  )
    httpmethod = "POST"
    restpath   = "{id}/"
    produces   = "application/json"
  {
    if ( FileExists( document ) )
      restSetResponse({
        "status"  = 201,
        "content" = {
          "id"    = id,
          "title" = title,
          "size"  = GetFileInfo( document ).size
        }
      });
    else
      restSetResponse({
        "status"  = 400,
        "content" = "Nothing uploaded"
      });
  }
}
和一个简单的HTML文件来测试它:




提交
然后服务返回
500
HTTP状态代码和JSON响应:

{"Message":"The DOCUMENT parameter to the upload function is required but was not passed in."}
检查HTTP请求头显示这两个字段都已传入,但服务未接收它们

注释掉HTML表单中的
enctype
属性(因此它使用默认编码
application/x-www-form-urlencoded
),然后服务返回
400
HTTP状态代码和响应
Nothing Upload


如何解决这一问题?

要彻底混淆请求数据,请填充
表单
变量,但是,即使函数参数状态为
restargsource=“FORM”
,当
enctype
不是
application/x-www-form-urlencoded
时,该值不会作为参数传递给REST服务

Adobe的文章证实了这一点:

表单参数:

在许多情况下,您必须处理在REST服务的表单中输入的数据。您可以使用此数据在数据库中创建新条目(
POST
)或更新现有记录(
PUT
)。如果使用表单字段,请将
restargsource
设置为
form
。这将提取请求中存在的数据,并使其可用于进一步处理。此外,在以表单字段形式发送数据时,必须将内容类型标题设置为
application/x-www-form-urlencoded

但是,可以通过将使用
restargsource=“form”
的参数更改为
form
变量中明确限定范围的参数来解决此问题

因此,用户可以这样修改服务:

component
  restpath = "test"
  rest     = true
{
  remote void function upload(
    required numeric id       restargsource = "Path"
  )
    httpmethod = "POST"
    restpath   = "{id}/"
    produces   = "application/json"
  {
    param name="form.document" type="string";
    param name="form.title"    type="string";

    if ( FileExists( form.document ) )
      restSetResponse({
        "status"  = 201,
        "content" = {
          "id"    = id,
          "title" = form.title,
          "size"  = GetFileInfo( form.document ).size
        }
      });
    else
      restSetResponse({
        "status"  = 400,
        "content" = "Nothing uploaded"
      });
  }
}