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

标签 php android file-upload retrofit2 multipart

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

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

@Multipart
@POST("URL/uploadImages.php")
Call<Response> uploaImages(
        @Part List< MultipartBody.Part> files );

发送文件代码

  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();
            }
        });

    }

这是我的 PHP 代码。

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
        }
    }
}

解决方案:

我发现了问题..我必须将 MultipartBodt.Part 的名称从 "file""file[]"。并在 $_FILES['file'] 中接收它们......和你一样使用传统形式...因为我将内容作为表单数据发送 所以修改我的 preparFfile() 方法。

最佳答案

在四处搜索和询问之后,这里有一个完整的、经过测试的、独立的解决方案。

1.创建服务接口(interface)。

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-上传图片方法

我从 onActivityResult() 方法传递了一个 URI 列表,然后我在 FileUtiles 的帮助下获得了实际的文件路径“类的链接已被注释”

 //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-我的php代码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);
?>

关于php - 如何使用 Retrofit 2 和 php 作为后端在一个请求中上传多张图片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43034437/

相关文章:

android - 在 LinearLayout 中重叠 TextView

java - 如何根据用户输入自动创建复选框

android - 如何使用 Ionic 和 Cordova 修复 Android 应用程序中的漏洞问题

iphone - 从 iPhone 应用程序使用 AFNetworking 上传视频

php - 站点地图不读取 javascript 链接

PHP/MySQL : querying MySQL with an array and getting results in an array

java - java中的多部分文件上传检查mime类型

php - 验证可以在 Laravel 验证中附加的多个文件的最大数量

php - 将 WHERE 原因添加到 COUNT 查询

javascript - 两个谷歌饼图中只有一个显示