使用改造2.0进行多文件上传

时间:2016-01-11 14:38:56

标签: php android file-upload multipart retrofit2

我目前正在处理应用程序的一部分,用户需要从库中选择一些图像,然后将这些图像上传到服务器。对于上传,我使用multipart进行改造2.0。

在资源https://futurestud.io/blog/retrofit-2-how-to-upload-files-to-server之后,当我只使用一个文件时,我成功地实现了它,但是我希望在一个会话中用户选择将所有图像上传到服务器。

环顾四周,我发现"Retrofit" multiple images attached in one multipart request讨论了@partmap注释,它似乎是正确的匹配但是我无法理解我将如何迭代我需要上传的图像?

有人可以指出我正确的实施吗?

同时检查: 1。Retrofit(2.0 beta2) Multipart file upload doesn't work 2。Upload multiple image with same name as array Retrofit 2.0.0-beta2

3 个答案:

答案 0 :(得分:0)

我只想尝试解决类似案例,但我所拥有的是大量文件。

我试图用循环来解决它:

recordsDirectory.mkdirs();
final File[] list_files = recordsDirectory.listFiles();
int cont = list_files.length;
for (int i = 0; i < cont; i++) {
    final File ref_file = list_files[i];
    String source_filepath = ref_file.getPath();
    RequestBody requestBody =
                RequestBody.create(MediaType.parse("multipart/form-data"), ref_file);
    Call<DeliveryResponse> call = apiService.upload(requestBody, description);
    call.enqueue(new Callback<DeliveryResponse>() {
        @Override
        public void onResponse(Response<DeliveryResponse> response, Retrofit retrofit) {
            Log.v(TAG, "[" + TAG + "] Upload success. status: " + response.toString());
            DeliveryResponse deliveryResponse = response.body();
            Log.v(TAG, "response code: " + deliveryResponse.mStatus);
            Log.v(TAG, "response code: " + response.code());
            Log.v(TAG, "ref_file: " + ref_file.getPath());
            if (response.isSuccess()) {
                Log.i(TAG, "[" + TAG + "] The server has response with a status distinct to 200.");
            }
            else {
                if (deliveryResponse.mStatus == 1) {
                    Log.i(TAG, "[" + TAG + "] The server has response with 1 as status.");
                    boolean deleted = ref_file.delete();                        
                } else {
                    Log.i(TAG, "[" + TAG + "] The server has response with 0 as status.");
                }
            }
        }

        @Override
        public void onFailure(Throwable t) {
            Log.e("Upload", t.getMessage());
        }
    });
}

/***********************************************
 RETROFIT API
 ************************************************/
public interface MyApiEndpointInterface {
    @Multipart
    @POST("/elderbask/api/sensors/accelerometer")
    Call<DeliveryResponse> upload(
        @Part("myfile\"; filename=\"image.png\" ") RequestBody file,
        @Part("description") String description
    );
}

public static class DeliveryResponse {

    @SerializedName("status")
    int mStatus;

    public DeliveryResponse(int status) {
        this.mStatus = status;
    }

    public String toString(){
        return "mStatus: " + this.mStatus;
    }

}

但是这个解决方案并没有像我预期的那样好。我有很多超时异常,错误的硬编码文件非常糟糕。

答案 1 :(得分:0)

由于我没有设法使用改造解决问题,我最终使用了okhttp库,它给了我所需要的东西,这里是我使用的代码示例,我希望可以帮助某人

构建请求正文:

                    okhttp3.RequestBody requestBody = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM)
                        .addPart(okhttp3.Headers.of("Content-Disposition:", "form-data; name=\"myfile\"; filename=\"image" + ImageNumber + ".jpg\""),
                                okhttp3.RequestBody.create(MEDIA_TYPE_JPG, new File(ImagePath)))
                        .build();

准备请求:

                         request = new okhttp3.Request.Builder()
                            .header("Authorization", "Client-ID " )
                            .url(YOUR URL)
                            .post(requestBody)
                            .build();

启动与服务器的连接:

                    try {
                    okhttp3.Response response = client.newCall(request).execute();
                    if (!response.isSuccessful())
                        throw new IOException("Unexpected code " + response);
                        System.out.println(response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }

答案 2 :(得分:0)

呜!我做了,你可以尝试这样做(改造2)

    //1. What We Need From Server ( upload.php Script )
    public class FromServer {
        String result;
    }

    //2. Which Interface To Communicate Our upload.php Script?
    public interface ServerAPI {

        @Multipart
        @POST("upload.php")//Our Destination PHP Script
        Call<List<FromServer>> upload(
                @Part("file_name") String file_name,
                @Part("file") RequestBody file);

         Retrofit retrofit =
                new Retrofit.Builder()
                        .baseUrl("http://192.168.43.135/retro/") // REMEMBER TO END with /
                        .addConverterFactory(GsonConverterFactory.create())
                 .build();
    }


    //3. How To Upload
    private void upload(){

            ServerAPI api = ServerAPI.retrofit.create(ServerAPI.class);

            File from_phone = FileUtils.getFile(Environment.getExternalStorageDirectory()+"/aa.jpg"); //org.apache.commons.io.FileUtils
            RequestBody to_server = RequestBody.create(MediaType.parse("multipart/form-data"), from_phone);

            api.upload(from_phone.getName(),to_server).enqueue(new Callback<List<FromServer>>() {
                @Override
                public void onResponse(Call<List<FromServer>> call, Response<List<FromServer>> response) {
                    Toast.makeText(MainActivity.this, response.body().get(0).result, Toast.LENGTH_SHORT).show();
                }
                @Override
                public void onFailure(Call<List<FromServer>> call, Throwable t) { }
            });


         }

//4. upload.php
<?php

    $pic = $_POST['file_name'];

    $pic = str_replace("\"", "", $pic); //REMOVE " from file name

    $f = fopen($pic, "w");
    fwrite($f,$_POST['file']);
    fclose($f);

    $arr[] = array("result"=>"Done");
    print(json_encode($arr));
?>