我正在尝试使用multipart / form-data发送POST。我遇到了一些问题,这些问题在这个论坛得到解决,比如额外的引用以及如何发送几个文件。但是现在,我想在一个数组中发送带有唯一名称的文件。我将附上两个文件来更好地表达我想要做的事情。
我收到这样的文件......
我希望收到这样的文件......
是否可以使用改装2更改车身数据结构?我想将mimetype数据从multipart / form-data更改为image / jpeg。
一些代码
HashMap<String, RequestBody> files = attachFile();
api.createPlant(plant.getName(),
plant.getSize(), plant.getPhSoil(), plant.getEcSoil(), plant.getGardenId(), files)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<Plant>() {
@Override
public final void onCompleted() {
Log.e(TAG, "on completed");
}
@Override
public final void onError(Throwable e) {
Log.e(TAG, e.getMessage());
}
@Override
public final void onNext(Plant response) {
mBody.setText(response.toString());
}
});
private HashMap<String, RequestBody> attachFile() {
ArrayList<String> listOfNames = new ArrayList<>();
listOfNames.add("images");
listOfNames.add("mango-lg2");
HashMap<String, RequestBody> map = new HashMap<>(listOfNames.size());
RequestBody file = null;
File f = null;
for(int i = 0, size = listOfNames.size(); i<size;i++){
try {
File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
f = new File(folder, listOfNames.get(i) + ".jpg");
Bitmap bitmap = convertFileToBitmap(f);
if(bitmap != null){
FileOutputStream fos = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.JPEG, 0 /*ignored for PNG*/, fos);
fos.flush();
fos.close();
}else{
Log.i("INFO", "imageNotFound");
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
file = RequestBody.create(MediaType.parse("multipart/form-data"), f);
map.put("file\"; filename=\"" + listOfNames.get(i) + ".jpg",file);
file = null;
f = null;
}
return map;
}
答案 0 :(得分:0)
我使用MultipartBody.Builder解决了我的问题,并使用RequestBody发送数据。
#trim(data)#
辅助方法
MultipartBody.Builder builder = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("name", plant.getName())
.addFormDataPart("size", String.valueOf(plant.getSize()));
ArrayList<File> files = new ArrayList<>();
File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
files.add(new File(folder, "images.jpg"));
files.add(new File(folder, "mango-lg2.jpg"));
builder = addImagesToRequestBody(builder, files);
api.createPlant(builder.build())
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<Plant>() {
@Override
public final void onCompleted() {
Log.e(TAG, "on completed");
}
@Override
public final void onError(Throwable e) {
Log.e(TAG, e.getMessage());
}
@Override
public final void onNext(Plant response) {
mBody.setText(response.toString());
}
});