我做了什么:
我正在play框架中使用POST方法开发Rest Web服务(使用Java)。我确实创建了简单的 Web 服务 POST API,并从客户端调用它。
我想要什么:
在此,我想将多个图像作为请求中的参数从客户端(android/IOS/web)传递给服务。但我没有得到任何与此相关的 API/教程。
我确实尝试将一张图像传递给该服务。但是当我传递图像请求时,我在 "FilePart file = body.getFile("img1")"
行中得到 null。
在Application.java中:
public static Result sampleMethod() {
ObjectNode result = Json.newObject();
result.put("message", "WS - Sample method");
MultipartFormData body = request().body().asMultipartFormData();
FilePart file = body.getFile("img1");
return ok(result);
}
在路由文件中:
POST /sampleMethod controllers.Application.sampleMethod()
在Client.java中:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost:9000/sampleMethod");
File file = new File("<<image path>>");
if(file.exists())
System.out.println("File exist");
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/jpeg");
mpEntity.addPart("img1", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
当我添加日志“Logger.info(request().body().toString());”时我得到以下值。请求有什么问题吗?
DefaultRequestBody(None,None,None,None,None,Some(MultipartFormData(Map(),List(),List(BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map()), BadPart(Map())),List())),false)
有人已经这样做了吗?谁能帮我做这个吗?
最佳答案
您可以发布多个文件并通过以下方式从请求中获取它们:
MultipartFormData body = request().body().asMultipartFormData();
FilePart picture1 = body.getFile("file1");
FilePart picture2 = body.getFile("file2");
“file1”和“file2”是后查询参数的名称。
关于java - Play框架-在post请求中传递多个图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30190052/