我已经尝试了Internet上所有可用的方法,但没有任何方法适合我。
我正在尝试以单个键值发送图像
{
files[]
}
这是我的界面
public interface UserClient {
@Multipart
@POST(".")
Call<JsonElement> upload(
@Part("text") RequestBody text,
@Part("image") RequestBody image,
@Part("login") RequestBody login,
@Part List<MultipartBody.Part> files
);
}
这是我的上传方法
public void uploadFiles(String text) {
QBUser user = SharedPrefsHelper.getInstance().getQbUser();
String userName = user.getFullName();
String image = "https://image.flaticon.com/icons/svg/146/146031.svg";
String URL = URLs.URL_POST + user.getPhone() + "/";
RequestBody textPart = RequestBody.create(MultipartBody.FORM, text);
RequestBody imagePart = RequestBody.create(MultipartBody.FORM, image);
RequestBody loginPart = RequestBody.create(MultipartBody.FORM, userName);
//list of files
List<MultipartBody.Part> filesList = new ArrayList<>();
for (int i = 0; i < arrayList_FilePath.size(); i++) {
filesList.add(prepareFilePart("files" + i, arrayList_FilePath.get(i)));
}
//Create retrofit instance
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(URL)
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
UserClient client = retrofit.create(UserClient.class);
Log.i(TAG, "uploadFiles: " + filesList);
Call<JsonElement> call = client.upload(textPart, imagePart, loginPart, filesList);
call.enqueue(new Callback<JsonElement>() {
@Override
public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
finish();
Toast.makeText(getApplicationContext(), "Successful: " + response.message(),
Toast.LENGTH_LONG).show();
Log.i(TAG, "onResponse: " + response.body() + response.message());
}
@Override
public void onFailure(Call<JsonElement> call, Throwable t) {
Toast.makeText(getApplicationContext(), "failed", Toast.LENGTH_LONG).show();
}
});
}
这是preparefilePart方法
public MultipartBody.Part prepareFilePart(String partName, String path){
long imagename = System.currentTimeMillis();
File file = new File(path);
RequestBody requestBody = RequestBody.create(
MediaType.parse("image/*"),
file
);
return MultipartBody.Part.createFormData(partName, imagename + ".jpeg" ,requestBody);
}
如果我仅发送文本请求而没有图像,则它可以正常工作,但是当我发送图像时,它无法正常工作
它给出错误代码500内部服务器错误,主体中具有空响应
注意:Api在邮递员中表现出色
最佳答案
文件未上传,因为文件创建不正确
感谢github,我找到了一种正确创建文件的方法
GitHub link for creating file
还根据此答案在我的代码中做了一些更改
link for stackoverflow answer