php - @Part List< MultipartBody.Part> 在 php 中

标签 php android retrofit

我正在使用此功能发布多张图片

@Multipart
@POST("addad")
Call<resultsmodel> addad(
        @Part List< MultipartBody.Part> files ,
        @Part MultipartBody.Part file,
        @Part("external_store") RequestBody external_store,
        @Part("inner_store") RequestBody inner_store,
        @Part("sectionId") RequestBody sectionId,
        @Part("title") RequestBody title,
        @Part("branchId") RequestBody branchId,
        @Part("branch_type") RequestBody branch_type,
        @Part("user") RequestBody user,
        @Part("year") RequestBody year,
        @Part("view_number") RequestBody view_number,
        @Part("type") RequestBody type,
        @Part("price") RequestBody price,
        @Part("city_id") RequestBody city_id,
        @Part("district_id") RequestBody district_id,
        @Part("lat") RequestBody lat,
        @Part("lon") RequestBody lon,
        @Part("details") RequestBody details,
        @Part("country") RequestBody country


);

我想知道如何在 php 中接收这个图像数组

最佳答案

以下是一些适用于 Android 的示例 PHP 和 Java 代码。请参阅 PHP 代码下方的 Android Java 示例代码。

PHP (upload.php):

<?php

$attachment = $_FILES['attachment'];
define ("MAX_SIZE","9000");
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");

// Method to extract the uploaded file extention
function getExtension($str)
{
         $i = strrpos($str,".");
         if (!$i) { return ""; }
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
}

// Method to extract the uploaded file parameters
function getFileAttributes($file)
{
    $file_ary = array();
    $file_count = count($file['name']);
    $file_key = array_keys($file);

    for($i=0;$i<$file_count;$i++)
    {
        foreach($file_key as $val)
        {
            $file_ary[$i][$val] = $file[$val][$i];
        }
    }
    return $file_ary;
}

// Check if the POST Global variable were set
if(!empty($attachment) && isset($_POST['dirname']))
{   
    $dirname = $_POST['dirname'];

    $uploaddir = "/var/www/html/uploads/".$dirname."/";

    //Check if the directory already exists.
    if(!is_dir($uploaddir)){
        //Directory does not exist, so create it.
        mkdir($uploaddir, 0777, true);
    }   

    $file_attributes = getFileAttributes($attachment);
    //print_r($file_attributes);

    $count = count($file_attributes);
    $response["status"] = array();
    $response["count"] = $count; // Count the number of files uploaded
    array_push($response["status"], $file_attributes);

    $file_dirs = array();

    foreach($file_attributes as $val)
    {       
        $old_file = $val['name'];
        $ext = getExtension($old_file);
        $ext = strtolower($ext);

        if(in_array($ext, $valid_formats))
        {
            $response["files"] = array();
            $new_file = date('YmdHis',time()).mt_rand(10,99).'.'.$ext;
            move_uploaded_file($val['tmp_name'], $uploaddir.$new_file);
            $file_dirs[] = 'http://192.168.50.10/gallery/uploads/'.$dirname."/".$new_file;
        }
        else
        {
            $file_dirs[] = 'Invalid file: '.$old_file;
        }
    }

    array_push($response["files"], $file_dirs);

    echo json_encode($response);
}
?>

安卓:

上传服务接口(interface)FileUploadService.java:

public interface FileUploadService {
    @Multipart
    @POST("upload.php")
    Call<ResponseBody> uploadMultipleFilesDynamic(
            @PartMap() Map<String, RequestBody> partMap, /* Associated with 'dirname' POST variable */
            @Part List<MultipartBody.Part> files); /* Associated with 'attachment[]' POST variable */
}

不同类上的 uploadPhotos() 方法,例如上传 Activity .java:

public void uploadPhotos(final List<Uri> uriList, final String folderName)
{
    List<MultipartBody.Part> parts = new ArrayList<>();
    for(Uri uri: uriList){
        parts.add(prepareFilePart("attachment[]", uri)); // Note: attachment[]. Not attachment
    }

    RequestBody requestBodyFolderName = createPartFromString(folderName);
    HashMap<String, RequestBody> requestMap = new HashMap<>();
    requestMap.put("dirname", requestBodyFolderName); // Note: dirname

    FileUploadService service = RetrofitClient.getApiService();
    Call<ResponseBody> call = service.uploadMultipleFilesDynamic(requestMap, parts);

        call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

            if(response.code() == 200)
            {
                // multiple dynamic uploads were successful
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {

            // errors

        }
    });
}

prepareFilePart() 方法:

private MultipartBody.Part prepareFilePart(String partName, Uri fileUri) {

    File file = new File(fileUri.getPath());

    // create RequestBody instance from file
    RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);

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

createPartFromString() 方法:

private RequestBody createPartFromString(String descriptionString) {
    return RequestBody.create(MediaType.parse("multipart/form-data"), descriptionString);
}

最后是 RetrofitClient.java 类:

public class RetrofitClient {

    private static final String ROOT_URL = "http://192.168.50.10/gallery/";

    public RetrofitClient() { }

    private static Retrofit getRetroClient() {
        return new Retrofit.Builder()
                .baseUrl(ROOT_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    public static FileUploadService getApiService() {
        return getRetroClient().create(FileUploadService.class);
    }
}

关于php - @Part List< MultipartBody.Part> 在 php 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44024529/

相关文章:

php - Laravel 4 - 文件上传

php - 在PHP中删除多维数组中特定键的重复值但删除最后一个?

java - Android中如何获取ArrayList的模型数据类型?

java - 创建具有不同请求类型的请求数据类

java - Retrofit - 如何在Retrofit中错误处理NumberFormatException?

php - ZLIB inflate 在 PHP 中给出 'data error'

php - 带有链接的可点击行

java - ArrayAdapter - 如何停止 getView 调用?

android - 多种字体在应用程序中不工作

android - 如何在 android retrofit 1.9 中从 List 发送多个 @Field?