2
我從我的Android應用程序向運行Play框架應用程序的服務器發送視頻文件和其他一些數據,我使用combination的multipartEntity
和Volley
將Post請求發送到服務器。在Play框架中解析多部分請求
我需要parse
在我的Controller中收到multipartEntity
請求,並將視頻存儲在服務器上的文件夾中,並將其餘數據發送到mySQL DB。
MultipartRequest:
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");
}
}
它是multipart/form-data類型,我編輯了我的問題向您展示我的MultipartEntityBuilder的構造函數,我嘗試使用您的代碼,但不成功,您能否詳細說明我如何使用您的代碼。 – Johntk 2015-04-02 20:16:33