我遇到了一个客户的问题,该客户正在使用一些疯狂的东西(它可能并不疯狂,我真的是对我自己不熟悉;))ruby rails 插件来处理带有附加数据的图像的上传。他们说服务器正在寻找信息的方式是
{
"objectname"{
"field"=>"value"
"field"=>"value"
"photo"=>#<ActionDispatch::Http::UploadedFile:0x00000004864fd0 @original_filename="avatar.png", @content_type="image/png",
@headers="Content-Disposition: form-data; name=\"aPhoto\"; filename=\"avatar.png\"\r\nContent-Type: image/png\r\n",
@tempfile=#<File:/tmp/RackMultipart20140211-8-1456165191981>
}
}
问题是使用 MultiPartEntity(这是他们说要使用的)我所能做的就是让服务器看到这个
{
"field"=>"value"
"field"=>"value"
"photo"=>#<ActionDispatch::Http::UploadedFile:0x00000004864fd0 @original_filename="avatar.png", @content_type="image/png",
@headers="Content-Disposition: form-data; name=\"aPhoto\"; filename=\"avatar.png\"\r\nContent-Type: image/png\r\n",
@tempfile=#<File:/tmp/RackMultipart20140211-8-1456165191981>
}
事实证明,额外的包裹层很困难。这是我的方法,我怎样才能在那个键“objectname”下实现那个额外的层?
MultipartEntity multiPartEntity = new MultipartEntity(HttpMultipartMode.STRICT, null, Charset.forName("UTF-8"));
ByteArrayBody imageByteArrayBody = new ByteArrayBody(imageBytes, "image/png", "avatar.png");
FormBodyPart imageFormBodyPart = new FormBodyPart("photo", imageByteArrayBody);
// sanity checks to make sure the headers are right
imageFormBodyPart.addField("Content-Disposition", "form-data; name=\"aPhoto\"");
imageFormBodyPart.addField("name", "aPhoto");
imageFormBodyPart.addField("filename", "avatar.png");
imageFormBodyPart.addField("Content-Type", "image/png");
// add the image body part to the multipart entity
multiPartEntity.addPart(imageFormBodyPart);
// add customer data
Map<String, String> customerMap = user.getUserMap();
// loop through the fields
for (Map.Entry<String, String> entry : customerMap.entrySet())
{
// create a new form part with the key as the name and the value as the value
FormBodyPart body = new FormBodyPart(entry.getKey(), new StringBody(entry.getValue()));
// sanity checking the headers are right
body.addField("Content-Disposition", "form-data; name=\"" + entry.getKey() + "\"");
body.addField(entry.getKey(), entry.getValue());
// add the part to the multipart entity
multiPartEntity.addPart(body);
}
postRequest.setEntity(multiPartEntity);
postRequest.setHeader(KEY_AUTHORIZATION, VALUE_AUTHORIZATION);
HttpResponse response = httpClient.execute(postRequest);
我知道这有点晚了。但我最近偶然发现了一个类似的问题。对我有用的解决方案是调整 rails 端的代码以删除额外的参数包装。根据我的研究,MultipartEntity
无法嵌套部件
我是一名优秀的程序员,十分优秀!