I am making an app in which user can select multiple images and upload them to the server. I am using PHP as a backend and retrofit2
I tried all answers on stackoverflow but still did not resolve it.
@Multipart
@POST("URL/uploadImages.php")
Call<Response> uploaImages(
@Part List< MultipartBody.Part> files );
code for sending 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();
}
});
}
here is my php code.
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:
I figured out the problem ..I have to change the name of the MultipartBodt.Part
from
"file"
to "file[]"
.and receive them in $_FILES['file']
... the same as you do with traditional form ... because I am sending the content as a form-data
so modify my preparFfile()
method.
after searching and asking around, here is a full, tested and self-contained solution.
1.create the service interface.
and the Response.java
}
2- uploadImages method
I pass a list of URI from
onActivityResult()
method, then I get the actual file path with the help of FileUtiles "the link to the class is commented"and the helper method used above
3-My php code image_uploader.php: