我正在从我的Android应用程序向运行Play框架应用程序的服务器发送视频文件和一些其他数据,我正在使用multipartEntity
和Volley
的组合向服务器发送Post请求。
我需要在我的控制器中parse
接收到的multipartEntity
请求,并将视频存储在服务器上的文件夹中,然后将其余数据发送到mySQL数据库。
多部分请求:
private static final String FILE_PART_NAME = "fileKey";
public MultipartRequest(String url, File file, Map<String, String> mStringPart,
Response.Listener<String> listener,
Response.ErrorListener errorListener)
super(Method.POST, url, errorListener);
mListener = listener;
mFilePart = file;
this.mStringPart = mStringPart;
entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
buildMultipartEntity();
}
private void buildMultipartEntity() {
entity.addPart(FILE_PART_NAME, new FileBody(mFilePart));
for (Map.Entry<String, String> entry : mStringPart.entrySet()) {
entity.addTextBody(entry.getKey(), entry.getValue());
}
}
@Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
httpentity = entity.build();
httpentity.writeTo(bos);
} catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
到目前为止,这是我的控制器:
public static Result uploadFile(){
RequestBody body = request().body();
Http.MultipartFormData multippartBody = body.asMultipartFormData();
if(multippartBody != null) {
return ok("Got: " + "Hi");
}
else {
return badRequest("Expecting text/plain request body");
}
}
我想我需要某种迭代器来从multippartBody
中提取视频和其他数据,但我不确定如何实现
编辑
更新的控制器:
public static Result jsonPost(){
RequestBody body = request().body();
Http.MultipartFormData multippartBody = body.asMultipartFormData();
Http.MultipartFormData.FilePart imageFile = body.getFile(fileKey);
if(multippartBody != null) {
return ok("Got: " + "hi");
}
else {
return badRequest("Expecting text/plain request body");
}
}
}
我在fileKey上播放时遇到找不到符号错误?
编辑正常工作
public static Result jsonPost(){
RequestBody body = request().body();
Http.MultipartFormData multippartBody = body.asMultipartFormData();
Http.MultipartFormData.FilePart imageFile = multippartBody.getFile("fileKey");
if(imageFile.getFile() != null) {
File file = imageFile.getFile();
String fileName = imageFile.getFilename();
File newDir = new File("/public/images/","MyApp");
if(!newDir.isDirectory()){
newDir.mkdirs();
System.out.println("Created dir");
}
if(newDir.canWrite()){
file.renameTo(new File(newDir, fileName));
}
return ok("Got: " + "it");
}
else {
return badRequest("Expecting text/plain request body");
}
}
检查请求标头中的内容类型,如果是应用程序/八位字节流,请使用
File file = request().body().asRaw().asFile();
如果是多部分/表单数据类型,则使用
play.mvc.Http.MultipartFormData body = request().body().asMultipartFormData();
play.mvc.Http.MultipartFormData.FilePart imageFile = body.getFile(imageKey);
File file = imageFile.getFile();