这是我用于多次上传到服务器的代码。这种格式在POSTMAN中正常工作,而不是使用retrofit2。任何人都可以帮助我
@Multipart
@POST("/api/answers/save")
Call<ResponseBody> upload(@Header("Authorization") String
authorization,@Part("input_answer") RequestBody answer_string,@Part
List<MultipartBody.Part> files);
检查这个
@NonNull
private RequestBody createPartFromJsonString(String json_answers_string) {
return RequestBody.create(
okhttp3.MultipartBody.FORM, json_answers_string);
}
检查一下,使用它将文件转换为多部分正文
@NonNull
private MultipartBody.Part prepareFilePart(String attachment_name, String absolute_path) {
File file = new File(absolute_path);
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
return MultipartBody.Part.createFormData(attachment_name, file.getName(), requestFile);
}
这用于多次上传
private void multipartUploadAudit(JSONObject json_object, List<String> FileNameWithAbsolutePath) {
progressBar.setVisibility(View.VISIBLE);
//convert jsonobject to string
Gson gson = new Gson();
String answers_string_json_obj = gson.toJson(json_object);
APIService mAPIService = ApiUtils.getAPIService();
List<MultipartBody.Part> parts = new ArrayList<>();
// add dynamic
for (int i = 0; i < FileNameWithAbsolutePath.size(); i++) {
String name = FileNameWithAbsolutePath.get(i).substring(FileNameWithAbsolutePath.get(i).lastIndexOf("/") + 1);
String names[] = name.split("\\.");
parts.add(prepareFilePart(names[0], FileNameWithAbsolutePath.get(i)));
}
// add another part within the multipart request
RequestBody answer_string = createPartFromJsonString(answers_string_json_obj);
// finally, execute the request
Call<ResponseBody> call = mAPIService.upload("Bearer " + sharedPrefUserData.getUserData().getAuthToken(), answer_string, parts);
// Call<ResponseBody> call = mAPIService.upload( description, parts);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
progressBar.setVisibility(View.GONE);
if (response.isSuccessful()) {
response.body(); // do something with that
Toast.makeText(AuditQuestionsLandingScreen.this, response.body().toString(), Toast.LENGTH_SHORT).show();
} else {
response.errorBody(); // do something with that
Toast.makeText(AuditQuestionsLandingScreen.this, response.errorBody().toString(), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
progressBar.setVisibility(View.GONE);
internetConnectionChecker.serverErrorAlert();
Log.v("Upload_error:", t.getMessage());
Toast.makeText(AuditQuestionsLandingScreen.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
答案 0 :(得分:0)
经过长时间的努力,我得到了答案。我通过使用gson将jsonobject转换为字符串而犯了一个错误。它添加了我的字符串 {&#34; nameValuePairs&#34;:{}}
所以我用过这个。 RequestBody.create(MediaType.parse(&#34;多部分/形状配合 数据&#34),将String.valueOf(JSON_OBJECT))