您如何访问在ColdFusion 11 REST服务中通过文件上传(使用enctype="multipart/form-data"
)发送的元数据(表单数据)?
模拟一个简单的服务:
component
restpath = "test"
rest = true
{
remove 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文件对其进行测试:
<!DOCTYPE html>
<html>
<body>
<form method="post"
action="http://localhost/rest/TestService/test/1/"
enctype="multipart/form-data">
<input type="text" name="title" value="File Title" /><br />
<input type="file" name="document" /><br />
<button type="submit">Submit</button>
</form>
</body>
</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 uploaded
。
如何解决?
为了彻底混淆请求数据,将填充FORM
变量,但是,即使函数参数状态为restargsource="form"
,当enctype
不是[application/x-www-form-urlencoded
时,该值也不会作为参数传递给REST服务。 C0]。
这已在Adobe的Getting started with RESTful web services in ColdFusion文章中得到证实:
表单参数:
[在许多情况下,您必须处理在REST服务中以表格形式输入的数据。您可以使用此数据在数据库中进行新输入(
POST
)或更新现有记录(PUT
)。如果使用表单字段,请将restargsource
设置为form
。这将提取请求中存在的数据,并使其可用于进一步处理。另外,在将数据作为表单字段发送时,必须将content-type标头设置为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"
});
}
}