如何使用Retrofit 2和php作为后端在一个请求中上传多个图像?

时间:2017-03-26 20:54:20

标签: php android file-upload retrofit2 multipart

我正在创建一个应用程序,用户可以在其中选择多个图像并将其上传到服务器。 我使用PHP作为后端和retrofit2

我在stackoverflow上尝试了所有答案,但仍然没有解决它。

  Retrofit builder = new Retrofit.Builder().baseUrl(ROOT_URL).addConverterFactory(GsonConverterFactory.create()).build();
        FileUploadService fileUploadService  = builder.create(FileUploadService.class);
        Call<Response> call = fileUploadService.uploadImages(list)
        for (Uri fileUri : path) {
            MultipartBody.Part fileBody = prepareFilePart("files", fileUri);
            images.add(fileBody);
        }


        Call<Response> call=fileUploadService.uploadImages(images);

        call.enqueue(new Callback<Response>() {
            @Override
            public void onResponse(Call<Response> call, Response<Response> response) {
                Log.e("MainActivity",response.body().toString());
                progressDialog.show();
            }

            @Override
            public void onFailure(Call<Response> call, Throwable t) {
                Toast.makeText(MainActivity.this, t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                Log.e("MainActivity",t.getLocalizedMessage());
                progressDialog.dismiss();
            }
        });

    }

发送文件的代码

if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
// Loop $_FILES to exeicute all files
foreach ($_FILES['files']['name'] as $f => $name) {     
    if ($_FILES['files']['error'][$f] == 4) {
        continue; // Skip file if any error found
    }          
    if ($_FILES['files']['error'][$f] == 0) {              
        if ($_FILES['files']['size'][$f] > $max_file_size) {
            $message[] = "$name is too large!.";
            continue; // Skip large files
        }
        elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
            $message[] = "$name is not a valid format";
            continue; // Skip invalid file formats
        }
        else{ // No error found! Move uploaded files 
            if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$name))
            $count++; // Number of successfully uploaded file
        }
    }
}

这是我的PHP代码。

MultipartBodt.Part

}

解决方案

我发现了问题..我必须更改"file"的名称 "file[]"$_FILES['file']。并在preparFfile()中收到...与传统表单相同...因为我将内容作为表单数据发送 所以修改我的App ID 435958876564133 : RROADSus Profile ID 830833833664593 : RROADSus User ID 596954487156779 : Janel Xxxxx User last installed this app via API N/A Issued 1487528725 (about a month ago) Expires Never Valid True Origin Web Scopes manage_pages, publish_pages, pages_manage_cta, publish_actions, public_profile 方法。

1 个答案:

答案 0 :(得分:3)

搜索并询问后,这是一个完整的,经过测试和自包含的解决方案。

1.创建服务界面。

public interface FileUploadService {

@Multipart
@POST("YOUR_URL/image_uploader.php")
Call<Response> uploadImages( @Part List<MultipartBody.Part> images);
      }

和Response.java

public class Response{
   private String error;
   private String message;
   //getters and setters

}

2- uploadImages方法

我从onActivityResult()方法传递了一个URI列表,然后在FileUtiles&#34的帮助下得到了实际的文件路径;该类的链接被评论为&#34;

 //code to upload
//the path is returned from the gallery 
void uploadImages(List<Uri> paths) {
    List<MultipartBody.Part> list = new ArrayList<>();
    int i = 0;
    for (Uri uri : paths) {
        String fileName = FileUtils.getFile(this, uri).getName();
        //very important files[]  
        MultipartBody.Part imageRequest = prepareFilePart("file[]", uri);
        list.add(imageRequest);
    }


    Retrofit builder = new Retrofit.Builder().baseUrl(ROOT_URL).addConverterFactory(GsonConverterFactory.create()).build();
            FileUploadService fileUploadService  = builder.create(FileUploadService.class);
    Call<Response> call = fileUploadService.uploadImages(list);
    call.enqueue(new Callback<Response>() {
        @Override
        public void onResponse(Call<Response> call, Response<Response> response) {
            Log.e("main", "the message is ----> " + response.body().getMessage());
            Log.e("main", "the error is ----> " + response.body().getError());

        }

        @Override
        public void onFailure(Call<Response> call, Throwable throwable) {
            Log.e("main", "on error is called and the error is  ----> " + throwable.getMessage());

        }
    });


}

以及上面使用的辅助方法

@NonNull
private MultipartBody.Part prepareFilePart(String partName, Uri fileUri) {
    // https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java
    // use the FileUtils to get the actual file by uri
    File file = FileUtils.getFile(this, fileUri);
            //compress the image using Compressor lib
            Timber.d("size of image before compression --> " + file.getTotalSpace());
            compressedImageFile = new Compressor(this).compressToFile(file);
            Timber.d("size of image after compression --> " + compressedImageFile.getTotalSpace());
    // create RequestBody instance from file
    RequestBody requestFile =
            RequestBody.create(
                    MediaType.parse(getContentResolver().getType(fileUri)),
                    compressedImageFile);

    // MultipartBody.Part is used to send also the actual file name
    return MultipartBody.Part.createFormData(partName, file.getName(), requestFile);
}

3-My php code image_uploader.php:

    <?php
$file_path = "upload/";
$full_path="http://bishoy.esy.es/retrofit/".$file_path;
$img = $_FILES['file'];
$response['message'] = "names : ";
if(!empty($img)){

   for($i=0;$i<count($_FILES['file']['tmp_name']);$i++){

     $response['error'] = false;
     $response['message'] =  "number of files recieved is = ".count($_FILES['file']['name']);
     if(move_uploaded_file($_FILES['file']['tmp_name'][$i],"upload/".$_FILES['file']['name'][$i])){
           $response['error'] = false;
     $response['message'] =  $response['message']. "moved sucessfully ::  ";

     }else{
     $response['error'] = true;
     $response['message'] = $response['message'] ."cant move :::" .$file_path ;

     }
    }
   }  
else{
     $response['error'] = true;
     $response['message'] =  "no files recieved !";
}

echo json_encode($response);
?>