我想通过复古适合将可变数量(用户定义)数量的文件上传到php(在这种情况下为照片),以便在我的php代码中使用。我相信我有改装代码,但我不确定如何执行php / slim代码,而且我似乎找不到答案。我已经搜索了。
所以我的android java就是这样的想法。要将可变数量的文件从手机上载到服务器。
caption[] = (cap1, cap2, cap3);
Uri[] = (user selected Uri, second uri, third uri, .....as selected);
x = Uri[].length;
private MultipartBody.Part prepareFilePart(String partName, Uri fileUri) {
File file = FileUtils.getFile(this, fileUri);
RequestBody requestFile =
RequestBody.create(
MediaType.parse(getContentResolver().getType(fileUri)),
file
);
return MultipartBody.Part.createFormData(partName, file.getName(),
requestFile);
}
List < MultipartBody.Part > parts = new ArrayList < > ();
While(x >= 0) {
photo = "photo" + x;
parts.add(prepareFilePart(photo, Uri[x]));
x = x - 1;
}
...
Call < ResponseBody > call = service.uploadMultipleFilesDynamic(description, parts);
致电
Call<ResponseBody> uploadMultipleFilesDynamic(
@Field("cap[]") ArrayList<String> capation[],
@Part List<MultipartBody.Part> files);
}
现在php是我有一些真正问题的地方,因为我不知道该如何接收。
目前对于1个文件,我会苗条地做类似的事情。
$response = array();
if (isset($_POST['cap']) &&
($_POST['IDs']) &&
($_POST['filenamev']) &&
$_FILES['image']['error'] === UPLOAD_ERR_OK) {
$upload = new pictureuploads();
$filep = $_FILES['image']['tmp_name'];
$capp = $_POST['cap'];
$ID = $_POST['IDs'];
$desc = $_POST['filenamev'];
if ($upload->savecapFile($filep, getFileExtension($_FILES['image']['name']), $desc, $ID, $capp)) {
$response['error'] = false;
$response['message'] = 'File Uploaded Successfullly';
} else {
$response['error'] = true;
$response['message'] = 'Required parameters are not available';
}
echo json_encode($response);
}
使用该方法。
public function savecapFile($filep, $extension, $desc, $ID, $timep)
{
move_uploaded_file($filep, $filedest);
}
所以我的问题是,如何接受php中可变数量的文件?
我想要的结果很简单。
随机上传了用户定义的文件数。现在,我的接收文件中必须有1对1链接。我不想为此担心,因此用户可以上传任意数量的照片。
答案 0 :(得分:0)
尝试以下一般示例:
$app->post('/savefile', function (Request $request, Response $response) {
$post = $request->getParsedBody();
$files = $request->getUploadedFiles();
// Custom validation
if (!isset($post['cap'], $post['IDs'], $post['filenamev'])) {
// Send validation error code 422
return $response->withJson([
'message' => 'Required parameters are not available',
])->withStatus(422);
}
// Validation passed
// Save files to this directory
$destination = 'storage/';
try {
$uploadedKeys = array_keys($files['image']['tmp_name']);
foreach ($uploadedKeys as $key) {
$tempFile = $files['image']['tmp_name'][$key];
$filename = $files['image']['name'][$key];
//$extension = pathinfo($filename , PATHINFO_EXTENSION);
if (!move_uploaded_file($tempFile, $destination)) {
throw new RuntimeException(sprintf('Upload failed: %s', $filename));
}
}
// Send OK
return $response->withJson([
'success' => true,
'message' => 'Files uploaded successfully',
])->withStatus(200);
} catch (Exception $exception) {
// Send error message
return $response->withJson([
'message' => sprintf('Upload failed with error: %s', $exception->getMessage()),
])->withStatus(500);
}
});