如何使用改造上传多个文件

时间:2018-04-05 11:36:40

标签: php android retrofit2

如何使用documentation

上传多个文件

我尝试使用以下代码上传文件:

ApiService

@Multipart
@POST("uploadData.php")
Call<ServerResponse> uploadFile(@Part MultipartBody.Part file,
                                @Part("name") RequestBody name,
                                @Part MultipartBody.Part img,
                                @Part("imgname") RequestBody imgname);

和上传方法:

private void uploadFile() {
    File file = new File(Environment.getExternalStorageDirectory() + "/Download/audio2.wav");
    File file2 = new File(Environment.getExternalStorageDirectory() + "/Download/Salty.png");

    RequestBody mFile = RequestBody.create(MediaType.parse("audio/*"), file);
    MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file.getName(), mFile);
    RequestBody filename = RequestBody.create(MediaType.parse("text/plain"), file.getName());

    RequestBody mFile2 = RequestBody.create(MediaType.parse("image/*"), file2);
    MultipartBody.Part fileToUpload2 = MultipartBody.Part.createFormData("file", file2.getName(), mFile2);
    RequestBody filename2 = RequestBody.create(MediaType.parse("text/plain"), file2.getName());

    ApiService uploadImage = ApiClient.getClient().create(ApiService.class);
    Call<ServerResponse> fileUpload = uploadImage.uploadFile(fileToUpload, filename, fileToUpload2, filename2);
    fileUpload.enqueue(new Callback<ServerResponse>() {
            @Override
            public void onResponse(Call<ServerResponse> call, Response<ServerResponse> response) {
                Toast.makeText(MainActivity.this, "Success " + response.message(), Toast.LENGTH_LONG).show();
                Toast.makeText(MainActivity.this, "Success " + response.body().toString(), Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFailure(Call<ServerResponse> call, Throwable t) {
                Log.d("TAG", "Error " + t.getMessage());
            }
    });
}

php代码

$result = array("success" => $_FILES["file"]["name"]);
$file_path = basename($_FILES['file']['name']);

$imgResult = array("success" => $_FILES["img"]["imgname"]);
$img_path = basename($_FILES['img']['imgname']);


if (move_uploaded_file($_FILES['img']['tmp_name2'], "$img_path") or
        move_uploaded_file($_FILES['file']['tmp_name'], "$file_path")) {
    $result = array("success" => "File successfully uploaded");
} else {
    $result = array("success" => "error uploading file");
}

echo json_encode($result, JSON_PRETTY_PRINT);

此代码仅适用于一个文件,我不知道原因,

任何帮助, 提前谢谢。

4 个答案:

答案 0 :(得分:3)

您必须使用以下改造在单个请求中更改代码以上传多个文件。

创建一个创建MultiPartBody.Part的函数,并自动获取其类型扩展。

public static MultipartBody.Part prepareFilePart(String partName, String fileUri) {
    File file = new File(fileUri);
    String mimeType= URLConnection.guessContentTypeFromName(file.getName());
    Log.e("mimeType",mimeType);
    //create RequestBody instance from file
    RequestBody requestFile = RequestBody.create(MediaType.parse(mimeType), file);
    //MultipartBody.Part is used to send also the actual file name
    return MultipartBody.Part.createFormData(partName, file.getName(), requestFile);
}

现在,在您的代码中,要上传多个文件,请按以下步骤创建ArrayList<MultiPartBody.Part>

public void uploadFile(){
    ArrayList<MultiPartBody.Part> files = new ArrayList<MultiPartBody.Part>();

    for(int i=0; i < selectedFiles.size; i++){
        files.add(prepareFilePart("file_"+(i+1), selectedFiles.get(i)));
        //Where selectedFiles is selected file URI list
    }

    RequestBody totalFiles = RequestBody.create(MediaType.parse("text/plain"), files.size);

    ApiService uploadImage = ApiClient.getClient().create(ApiService.class);
    Call<ServerResponse> fileUpload = uploadImage.uploadFile(files,totalFiles);
    fileUpload.enqueue(...);

}

并在ApiService中进行更改

@Multipart
@POST("uploadData.php")
Call<ServerResponse> uploadFile(@Part ArrayLisy<MultipartBody.Part> files, @Part("totalFiles") RequestBody totalFiles);

并在您的PHP文件中将代码更改为

$totalFiles = $_REQUEST['totalFiles'];
$successUpload = 0;

for($i=1; $i <= $totalFiles; $i++){
    $fileName = 'file_'.$i;
    if(move_uploaded_file($_FILES[$fileName]['tmp_name'],"Valid_file_path"){
        $successUpload += 1;
    }
}

echo $successUpload.' Files uploaded successfully.';

答案 1 :(得分:2)

无需在收到文件后从Android传递您的文件名,然后在此处获取该文件名(在PHP代码中)

@Multipart
@POST("uploadData.php")
Call<ServerResponse> uploadFile(@Part MultipartBody.Part file,
                                @Part MultipartBody.Part img);

文件上传Java代码

MultipartBody.Part audioFile= null;
        try {
            File file = new File(Environment.getExternalStorageDirectory() + "/Download/audio2.wav");
            if file != null) {                
                RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"),
                        file);
                audioFile = MultipartBody.Part.createFormData("AudioFile", file.getName(), requestFile);
            }
        }
        catch (Exception ex)
        {
            Log.d("UploadStatus", "Multipart Audio as exception occurs");
        }

MultipartBody.Part imageFile = null;
        try {
            File file = new File(Environment.getExternalStorageDirectory() + "/Download/Salty.png");
            if file != null) {                
                RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"),
                        file);
                imageFile = MultipartBody.Part.createFormData("ImageFile", file.getName(), requestFile);
            }
        }
        catch (Exception ex)
        {
            Log.d("UploadStatus", "Multipart Image as exception occurs");
        }


ApiService uploadImage = ApiClient.getClient().create(ApiService.class);
    Call<ServerResponse> fileUpload = uploadImage.uploadFile(audioFile, imageFile);
    fileUpload.enqueue(new Callback<ServerResponse>() {
            @Override
            public void onResponse(Call<ServerResponse> call, Response<ServerResponse> response) {
                Toast.makeText(MainActivity.this, "Success " + response.message(), Toast.LENGTH_LONG).show();
                Toast.makeText(MainActivity.this, "Success " + response.body().toString(), Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFailure(Call<ServerResponse> call, Throwable t) {
                Log.d("TAG", "Error " + t.getMessage());
            }
    });
PHP代码中的

访问两个文件,如

file 1    ==>   $_FILES["AudioFile"]["name"]

file 1    ==>   $_FILES["ImageFile"]["name"]

然后在这里获取你的文件名......

您必须避免在改装生成器上面临setLenient错误

Gson gson = new GsonBuilder()
        .setLenient()
        .create();

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(BASE_URL)
        .client(client)
        .addConverterFactory(GsonConverterFactory.create(gson))
        .build(); 

希望这会对你有帮助......

答案 2 :(得分:1)

如上所述@chintak的回答是正确的,你需要添加

Gson gson = new GsonBuilder()
.setLenient()
.create();

Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create(gson))
.build()

如您在上述评论中所述,您面临的是Lenient格式错误的异常。

答案 3 :(得分:0)

Api界面:

  @Multipart
        @POST("Shareds/AddShared")
        Call<ResponseBody> UPLOAD_PHOTO_CALL(
                @Part List<MultipartBody.Part> files);



List<MultipartBody.Part> parts = new ArrayList<>();

**and then fill your parts with for loop :D** 

RequestBody reqFile = RequestBody.create(compressedImgFile, MediaType.parse("image/*"));
            parts.add(MultipartBody.Part.createFormData("files", file.getName(), reqFile));



retrofit = new Retrofit.Builder()
                .baseUrl(TEST_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addConverterFactory(**ScalarsConverterFactory.create()**)
                .client(builder.build())
                .build();
        return retrofit;