我正在使用以下代码在聊天应用程序中将文件(pdf,docx,pptx等)从用户发送到用户。
public class UploadFile extends AsyncTask<String, Void, String> {
protected MessageModel mMessage;
File file ;
String mimeType = "";
public UploadFile(MessageModel msg, File file) {
super();
this.mMessage = msg;
this.file = file;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... params) {
String responseBodyText = null;
mimeType = mMessage.getMsgFileType();
MediaType MEDIA_TYPE = okhttp3.MediaType.parse(mimeType);
OkHttpClient client = new OkHttpClient();
try {
RequestBody req = new okhttp3.MultipartBody.Builder()
.setType(okhttp3.MultipartBody.FORM)
.addFormDataPart("chatFileUpload", file.getName(), RequestBody.create(MEDIA_TYPE, file)).build();
Request request = new Request.Builder()
.header("Authorization", "Bearer "+Constants.AUTH_TOKEN)
.addHeader("User-Agent", Constants.USER_AGENT)
.url(urlforFileUpload)
.post(req)
.build();
Response response = null;
response = client.newCall(request).execute();
if (!response.isSuccessful()) {
throw new IOException("Okhttp Error: " + response);
} else {
responseBodyText = response.body().string();
Log.d("PrintResponseBody", responseBodyText); // Print the response body here
}
} catch (IOException e) {
e.printStackTrace();
}
return responseBodyText;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
JSONObject msgFiles = new JSONObject();
if (result != null) {
try {
JSONObject responseObject = new JSONObject(result);
msgFiles.put("filename", responseObject.get("fileName"));
msgFiles.put("mimetype", responseObject.get("mimetype"));
msgFiles.put("filepath", responseObject.get("fileUploadPath"));
Log.d("PrintFileUploadPath", String.valueOf(responseObject.get("fileUploadPath")));
// Print the response upload file path with file name and extension;
//.... do other stuffs....
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
在logcat中,我的扩展名为'undefined'而不是正确的扩展名(.docx,.pptx等)。有人能告诉我哪种行为会引起这种行为吗?它合适吗?如果是,我该如何检查用户从服务器响应中接收哪种类型的文件?
我正在使用调试器的响应示例:
{
"status":"true",
"fileName":"1490691261587.undefined",
"fileUploadPath":"/uploads/chat_upload/1490691261587.undefined",
"mimetype":"file/file",
"msg":"File is uploaded successfully",
"downloadLink":"<a target=\"_blank\" href=\"/uploads/chat_upload/1490691261587.undefined\">New-Text-Document.txt909.txt</a>"
}
提前致谢。