【发布时间】:2017-08-19 10:53:57
【问题描述】:
我正在制作一个应用程序,用户可以在其中选择多个图像并将它们上传到服务器。 我使用 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
}
}
}
}
解决方案:
我发现了问题..我必须将MultipartBodt.Part 的名称从
"file" 到 "file[]". 并在 $_FILES['file'] 中接收它们...就像您使用传统形式一样...因为我将内容作为表单数据发送
所以修改我的preparFfile() 方法。
【问题讨论】:
标签: php android file-upload retrofit2 multipart