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

2024-01-15

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

我尝试了 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
        }
    }
}

}

Solution:

我解决了问题..我必须更改名称MultipartBodt.Part from "file" to "file[]".并接收它们$_FILES['file']...与传统表单相同...因为我将内容作为表单数据发送 所以修改我的preparFfile() method.


经过搜索和询问后,这是一个完整的、经过测试的、独立的解决方案。

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

我传递了一个 URI 列表onActivityResult()方法,然后我在 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);
?>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

  • Facebook API sdk 4.0 - 将照片发布到 Facebook

    我正在尝试创建一个应用程序 用户可以在其中浏览照片并将其从计算机提交到 Facebook 为此 他们首先必须将照片上传到服务器 然后使用 Facebook 请求将此图像发布到 Facebook 我正在使用多部分 表单数据 这就是我到目前为止
  • 如何在 Windows 上安装 Zend 框架

    安装 Zend Framework 就是这么简单 是的 对 好吧 我正在写一本初学者的书 有一件不太详细的事情是最重要的部分 安装该死的东西 浏览了几个小时的快速入门指南后 它只说 下载 Zend 添加包含目录 bla bla 然后就完成了
  • Android:捕获的图像未显示在图库中(媒体扫描仪意图不起作用)

    我遇到以下问题 我正在开发一个应用程序 用户可以在其中拍照 附加到帖子中 并将图片保存到外部存储中 我希望这张照片也显示在图片库中 并且我正在使用媒体扫描仪意图 但它似乎不起作用 我在编写代码时遵循官方的Android开发人员指南 所以我不
  • Android MediaExtractor seek() 对 MP3 音频文件的准确性

    我在使用 Android 时无法在eek 上获得合理的准确度MediaExtractor 对于某些文件 例如this one http www archive org download emma solo librivox emma 01
  • PHP 编码风格回归;在开关/外壳中

    我们正在尝试为我们的团队实施新的编码风格指南 当未找到 break 时 php codeniffer 会在 switch case 语句上打印警告 如下所示 switch foo case 1 return 1 case 2 return
  • 在gradle插件中获取应用程序变体的包名称

    我正在构建一个 gradle 插件 为每个应用程序变体添加一个新任务 此新任务需要应用程序变体的包名称 这是我当前的代码 它停止使用最新版本的 android gradle 插件 private String getPackageName
  • 从 Laravel 4 输入生成新数组

    我使用 Input all 从动态生成的表单中获取一些输入 我使用 jQuery 来允许用户添加字段 字段名称为 first names last names 和 emails input 变量现在看起来像这样 array size 4 t
  • 如何发布Android .aar源以使Android Studio自动找到它们?

    我正在将库发布到内部 Sonatype Nexus 存储库 Android Studio 有一个功能 可以自动查找通过 gradle 引用的库的正确源 我将 aar 的源代码作为单独的 jar 发布到 Nexus 但 Android Stu
  • 如何使用InputConnectionWrapper?

    我有一个EditText 现在我想获取用户对此所做的所有更改EditText并在手动将它们插入之前使用它们EditText 我不希望用户直接更改中的文本EditText 这只能由我的代码完成 例如通过使用replace or setText
  • 尝试在 ubuntu 中编译 android 内核时出错

    我正在尝试从源代码编译 Android 内核 并且我已经下载了所有正确的软件包来执行此操作 但由于某种原因我收到此错误 arm linux androideabi gcc error unrecognized command line op
  • 如何将 .xlsx 文件上传到 jenkins 作业

    如何将 xlsx 文件作为构建参数上传到 jenkins 作业 我尝试使用文件参数 但我发现该文件正在丢失其扩展名或原始格式 有什么方法可以从 jenkins UI 将 excel 文件上传到 jenkins 作业吗 In the file
  • 字符串相似度的算法(比Levenshtein和similar_text更好)? php, Js

    在哪里可以找到比 levenshtein 和 phpimilar text 方法更准确地评估错误字符的拼写的算法 Example similar text jonas xxjon similar echo similar returns 6
  • Jquery一键提交多个同名表单

    我有动态创建的循环表单 我需要一键提交所有表单 我正在遵循下面的代码 你能建议我怎么做吗 谢谢
  • session_start():无法解码会话对象

    我有时在使用 CodeIgniter 时遇到以下问题 错误 2019 03 05 19 57 26 gt 严重性 警告 gt session start 无法解码会话对象 会话已被销毁 system libraries Session Se
  • PHP 表单 - 带验证蜜罐

    我有以下内容 效果很好 但对垃圾邮件机器人开放 我想放入蜜罐 而不是验证码 下面的代码适用于验证姓名 电子邮件 消息 但我无法让它与蜜罐一起工作 任何人都可以查看 蜜罐 代码并告诉我如何修复它吗 我希望表单给出 success2 不允许垃圾
  • .isProviderEnabled(LocationManager.NETWORK_PROVIDER) 在 Android 中始终为 true

    我不知道为什么 但我的变量isNetowrkEnabled总是返回 true 我的设备上是否启用互联网并不重要 这是我的GPSTracker class public class GPSTracker extends Service imp
  • 如何在 PHP 5.6 中通过 php.ini 设置“verify_peer_name=false”SSL 上下文选项

    案例 我想打开 SSL 连接localhost而 SSL 证书是 FQDN 的问题 问题 没有进行特殊处理就行 下面的程序失败并显示以下消息 PHP Warning stream socket enable crypto Peer cert
  • Firebase 添加新节点

    如何将这些节点放入用户节点中 并创建另一个节点来存储帖子 我的数据库参考 databaseReference child user getUid setValue userInformations 您需要使用以下代码 databaseRef
  • 将 Intent 包装在 LabeledIntent 中以用于显示目的

    要求 我的应用程序中有一个 共享 按钮 我需要通过 Facebook 分享 我需要选择是否安装原生 Facebook 应用程序 我们的决定是 如果未安装该应用程序 则将用户发送到 facebook com 进行分享 当前状态 我可以检测何时
  • PHPUnit - 模拟 S3Client 无法正常工作

    库 aws aws sdk php 2 PHP 版本 PHP 5 4 24 cli 作曲家 json require php gt 5 3 1 aws aws sdk php 2 require dev phpunit phpunit 4

随机推荐