【问题标题】:Android : Send Multiple images as file to server using retrofit in an arrayAndroid:使用数组中的改造将多个图像作为文件发送到服务器
【发布时间】:2017-06-05 07:33:12
【问题描述】:

我需要将 4 个图像作为文件发送到服务器(我无法转换为位图或字符串),服务器应该接收数组中的所有 4 个文件(文件 [])仅作为数组。我如何使用 RETROFIT 在 android 中实现这一点

有关所需的服务器上传,请参见下文

D/OkHttp: pics=[image1,image2,image3,image4]&txt=&pic=true&type=img

【问题讨论】:

标签: java android xml


【解决方案1】:

要在改造 2 中上传图片,请尝试此代码

像这样创建 Api 接口:

@Multipart
@POST("uploadAttachment")
Call<MyResponse> uploadAttachment(@Part MultipartBody.Part filePart);

然后像这样上传文件:

File file = // initialize file here

MultipartBody.Part filePart = MultipartBody.Part.createFormData("pics", file.getName(), RequestBody.create(MediaType.parse("image/*"), file));

Call<MyResponse> call = api.uploadAttachment(filePart);

【讨论】:

  • 你的方法帮助了你
【解决方案2】:

最佳做法是一张一张上传图片。相反,如果您的请求失败,它将消耗时间/数据,因为它有许多图像。

但你可以做到这一点,请按照以下代码:

Retrofit Version: 'com.squareup.retrofit2:retrofit:2.1.0'

AddMediaMessageRequestEvent对象类:

public class AddMediaMessageRequestEvent implements Serializable {
    public String token;
    public Map<String, RequestBody[]> bodyMap;
}

MainActivity.java

AddMediaMessageRequestEvent request = new AddMediaMessageRequestEvent();
Map<String, RequestBody> map = new HashMap<>();
//"thumbFile" is your image file
RequestBody[] thumbBody = new RequestBody[3];
thumbBody[0] = RequestBody.create(MediaType.parse("image/jpg"), thumbFile);
thumbBody[1] = RequestBody.create(MediaType.parse("image/jpg"), thumbFile);
map.put(toRequestParams(thumbFile), thumbBody);
request.bodyMap = map

toRequestParams(//file)方法:

private String toRequestParams(File thumbFile) {
    // "thumb" is the API key
    return "thumb\"; filename=\"" + thumbFile.getName() + ".jpg\"";
}

改装电话:

Call<ResponseMessage> call = mApi.addMediaMessage(request.token, request.bodyMap);
call.enqueue(//new Callback())

API:

@Multipart
    @POST("/api/{id}/add-media-message")
    Call<ResponseMessage> addMediaMessage(
            @Header(AppConstants.HEADER_PARA_TOKEN) String token,
            @PartMap Map<String, RequestBody> params);

【讨论】:

  • 假设您的方法可以发送数组,我们如何在 api 的 "pics" 键处发送此地图
  • 也请告诉我在哪里可以找到 AddMediaMessageRequestEvent 类
  • "拇指\";是您的键名。 :) 生病编辑我的答案,那只是一个对象...
  • AddMediaMessageRequestEvent 是您的自定义类,提供的库,其中的令牌是什么?
  • 如果您的 API 服务中没有令牌密钥,您不想添加令牌
【解决方案3】:

试试这个 第1步。 接口类

@Multipart
@POST("/api/V1/CreateTicket")
Observable<DefaultResponse> postTicket(@Header("Authorization") String Auth, @Part("siteId") RequestBody site_id,
                                       @Part("incidentId") RequestBody incidentid, @Part("isEmergency") RequestBody emergency, @Part("ticketNotes") RequestBody note,
                                       @Part MultipartBody.Part[] attachment);

第 2 步。

MultipartBody.Part[] multipartTypedOutput = new MultipartBody.Part[image.size()];

    for (int index = 0; index < image.size(); index++) {
        Log.d("Upload request", "requestUploadSurvey: survey image " + index + "  " + image.get(index));
        File file2 = new File(image.get(index));
        RequestBody surveyBody = RequestBody.create(MediaType.parse("image/*"), file2);
        multipartTypedOutput[index] = MultipartBody.Part.createFormData("imageFiles[]", file2.getPath(), surveyBody);
    }

保重和享受......

【讨论】:

    【解决方案4】:

    这里是使用改造发送多张图片的代码

    MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);
        builder.addFormDataPart("event_name", eventName);
        builder.addFormDataPart("location", loacation);
        builder.addFormDataPart("longitude", longitude);
        builder.addFormDataPart("latitude", latitude);
        builder.addFormDataPart("is_private", isPublic);
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), coverImage);
        builder.addFormDataPart("cover_image", coverImage.getName(), requestBody);
        RequestBody requestBody1 = null;
    
        for (int i = 0, size = eventFiles.size(); i < size; i++) {
            requestBody1 = RequestBody.create(MediaType.parse("multipart/form-data"), eventFiles.get(i));
            builder.addFormDataPart("album_images" + "[" + i + "]", eventFiles.get(i).getName(), requestBody1);
        }
        RequestBody finalRequestBody = builder.build();
    
        final Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(RestClient.ROOT)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        RestClient.NetworkCall networkCall = retrofit.create(RestClient.NetworkCall.class);
    Call<EventResponse> response = networkCall.uploadEvent(Prefs.getAuth(App.getContext()), finalRequestBody);
    
     @POST(UPLOAD_EVENT)
        Call<EventResponse> uploadEvent(@Header("Authorization") String auth,@Body RequestBody body);
    

    【讨论】:

    • 您的解决方案只是将文件一个一个添加到请求中,它不会像我需要的那样创建一个数组
    • 它是我发送到服务器的图像数组
    • 如何将图像数组发送到服务器
    【解决方案5】:

    我终于用这种方法做到了

    MultipartBody.Part[] partfiles=new MultipartBody.Part[4];
    
    
            try{
                int size=imagesList.size();
                for(int i=0;i<imagesList.size();i++){
                    if(i<4){
    
                        try{
                            partfiles[i] = MultipartBody.Part.createFormData("pics["+i+"]",
                                    Calendar.getInstance().getTimeInMillis()+".jpg",
                                    RequestBody.create(MediaType.parse("image/*"),getJPEGFile(new File(imagesList.get(i)))));
                        }catch (Exception e){}
    
                    }
                }
    
            }catch (Exception e){}
    

    而 api 命中是

    Call<JsonObject> call=service.requestUpload(hello.getString("authorization",""),partfiles[0],partfiles[1],partfiles[2],partfiles[3]);
    

    和api接口是

    @Multipart
    @POST("api/myphotoupload")
    Call<JsonObject> requestUpload(@Header("Authorization") String headerToken,
                                    @Part MultipartBody.Part postImagesZero,
                                    @Part MultipartBody.Part postImagesOne,
                                    @Part MultipartBody.Part postImagesTwo,
                                    @Part MultipartBody.Part postImagesThree);
    

    【讨论】:

      【解决方案6】:

      @Part 注释必须提供名称或使用 MultipartBody.Part 参数类型。 (参数#1) 在 android studio 3.4 的界面中显示 @Part MultipartBody.Part[] 错误

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-06-17
        • 2020-01-05
        • 2019-06-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多