我有一个Windows Phone 8客户端发出以下帖子请求:
public async Task<string> DoPostRequestAsync(String URI, JSonWriter jsonObject, ObservableCollection<byte[]> attachments)
{
var client = new RestClient(DefaultUri);
var request = new RestRequest(URI, Method.POST);
request.AddParameter("application/json; charset=utf-8", jsonObject.ToString(), ParameterType.RequestBody);
// add files to upload
foreach (var a in attachments)
request.AddFile("picture", a, "file.jpg");
var content = await client.GetResponseAsync(request);
return content;
}
从RestSharp文档中我读到,通过向请求添加文件,它会自动作为“multipart / form-data”请求。
Play 2.1中的上传操作控制器如下:
@BodyParser.Of(BodyParser.Json.class)
public static Result createMessage() {
JsonNode json = request().body().asJson();
ObjectNode result = Json.newObject();
String userId = json.findPath("userId").getTextValue();
String rayz = json.findPath("message").getTextValue();
Http.MultipartFormData body = request().body().asMultipartFormData();
Http.MultipartFormData.FilePart picture = body.getFile("picture");
if (picture != null) {
String fileName = picture.getFilename();
String contentType = picture.getContentType();
File file = picture.getFile();
result.put("status", "success");
result.put("message", "Created message!");
return badRequest(result);
} else {
result.put("status", "error");
result.put("message", "Message cannot be created!");
return badRequest(result);
}
}
请注意,在application.conf上我设置了以下内容以增加大小限制(似乎不起作用):
# Application settings
# ~~~~~
parsers.text.maxLength=102400K
现在,每次我尝试发出POST请求时,我都会在调试器上注意到IsMaxSizeEsceeded变量始终为true,并且multipart变量为null。当我尝试使用以下控制器上传一个文件nu时,一切似乎都正常工作。大小不是问题,并且设置了多部分变量。
public static Result singleUpload() {
ObjectNode result = Json.newObject();
Http.MultipartFormData body = request().body().asMultipartFormData();
Http.MultipartFormData.FilePart picture = body.getFile("picture");
if (picture != null) {
String fileName = picture.getFilename();
String contentType = picture.getContentType();
File file = picture.getFile();
result.put("status", "success");
result.put("message", "File uploaded!");
return badRequest(result);
} else {
result.put("status", "error");
result.put("message", "File cannot be uploaded!");
return badRequest(result);
}
}
问题是附件/文件应该与JSON对象一起发送/上传到单个POST请求中的服务器而不是单独发送。
之前有没有人遇到过类似的问题?是否可以实现这一点 - 使用Play 2.1在一个POST请求中发送一个json对象和多个要上传到服务器上的文件?
答案 0 :(得分:8)
找到了做到这一点的方法。以防万一其他人试图在将来做类似的事情。
首先,必须以下列方式完成RestSharp客户端的请求:
public async Task<string> DoPostRequestWithAttachmentsAsync(String ext, JSonWriter jsonObject, ObservableCollection<byte[]> attachments) {
var client = new RestClient(DefaultUri);
var request = new RestRequest(ext, Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddParameter("json", jsonObject.ToString(), ParameterType.GetOrPost);
// add files to upload
foreach (var a in attachments)
request.AddFile("attachment", a, "someFileName");
var content = await client.GetResponseAsync(request);
if (content.StatusCode != HttpStatusCode.OK)
return <error>;
return content.Content;
}
现在进入播放控制器如下:
public static Result createMessage() {
List<Http.MultipartFormData.FilePart> attachments;
String json_str;
Http.MultipartFormData body = request().body().asMultipartFormData();
// If the body is multipart get the json object asMultipartFormData()
if (body!=null) {
json_str = request().body().asMultipartFormData().asFormUrlEncoded().get("json")[0];
attachments= body.getFiles();
}
// Else, if the body is not multipart get the json object asFormUrlEncoded()
else {
json_str = request().body().asFormUrlEncoded().get("json")[0];
attachments = Collections.emptyList();
}
// Parse the Json Object
JsonNode json = Json.parse(json_str);
// Iterate through the uploaded files and save them to the server
for (Http.MultipartFormData.FilePart o : attachments)
FileManager.SaveAttachmentToServer(o.getContentType(), o.getFile());
return ok();
}
因此,RestSharp端的错误似乎是json对象上的ParameterType.RequestBody;并且在控制器中,大小并没有真正改变任何东西..但重要的部分是不使用@ BodyParser.Of(BodyParser.Json.class),因为这会将整个请求体转换为json对象。与发送到服务器的文件相结合,会触发isMaxSizeExceeded标志。
最后,控制器中的多部分文件处理如上所示,唯一棘手的部分是附件是可选的,这意味着必须处理它。