如何使用Android应用程序中的其他字段将照片发送到服务器? [英] How to send Photos to server with additional fields in Android app?
本文介绍了如何使用Android应用程序中的其他字段将照片发送到服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试通过翻新将多张照片发送到服务器.我有这样的端点:
I try to send multiple photos to server with Retrofit. I have endpoint like this:
@Multipart
@POST("/v1/props")
Call<ModelProp> createProp(
@Header("x-auth") String token,
@Part List<MultipartBody.Part> photo
);
但是我不知道如何通过以下方式向此POST方法添加其他信息:
But I don't know how to add to this POST method additional information with:
int price;
String currency;
ArrayList<String> tags;
有人可以帮助我将此字段添加到经过改造的POST吗?
Can someone help me add this fields to POST with retrofit?
数组可能包含1000多个元素
edit: Array may have 1000+ elements
推荐答案
在Retrofit 2中,您可以通过以下方式将其与图像一起发送额外的数据:
In Retrofit 2, You can send it extra data with the image in the following way:
编辑:基于Ali Ghafari的答案,您还可以使用PartMap
Based on Ali Ghafari answer you can also use PartMap
public interface ApiInterface {
@Multipart
@POST("/v1/props")
Call<ModelProp> createProp(@Header("x-auth") String token,
@Part List<MultipartBody.Part> photo,
@PartMap Map<String, RequestBody> map
}
您可以像这样使用它:
List<MultipartBody.Part> parts = new ArrayList<>();
for (int i=0; i < upFileList.size(); i++){
parts.add(prepareFilePart("my_file["+i+"]", upFileList.get(i)));
}
Map<String, RequestBody> partMap = new HashMap<>();
partMap.put("price", createPartFromString(edtPrice.getText().toString()));
partMap.put("currency", createPartFromString(edtCurrency.getText().toString()));
partMap.put("tags", createPartFromString(new Gson().toJson(tagsArrayList));
Call<User> call = client.createProp(TokenUtils.getToken(this), partMap);
call.enqueue(new Callback<ModelProp>() {
@Override
public void onResponse(retrofit.Response<ModelProp> response, Retrofit retrofit) {
// consume response
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
});
prepareFilePart
方法
prepareFilePart
method
private MultipartBody.Part prepareFilePart(String partName, Uri fileUri){
File file = new File(fileUri.getPath(););
RequestBody requestBody = RequestBody.create(MediaType.parse(getContentResolver().getType(fileUri)), file);
return MultipartBody.Part.createFormData(partName, file.getName(),requestBody);
}
createPartFromString
方法
createPartFromString
method
public RequestBody createPartFromString(String string) {
return RequestBody.create(MultipartBody.FORM, string);
}
这篇关于如何使用Android应用程序中的其他字段将照片发送到服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文