所以我想使用retrofit
将图片上传到我的Slim framework API
。现在我可以在我的另一个项目中使用单独的.php
文件成功上传图像,该文件通过$_FILES
对象接收图像,这是
<?php
ini_set('display_errors',1);
ini_set('upload_max_filesize', '20M');
ini_set('post_max_size', '20M');
ini_set('max_input_time', 30000);
ini_set('max_execution_time', 30000);
require_once '../include/Functions.php';
$db = new Functions();
$result['error'] = true;
$result['message'] = 'Error occurred, try again1';
$userfk = $_POST['userid'];
$fileNames = array();
for($i = 0; $i < count ( $_FILES ['file'] ['name'] ); $i ++) {
try {
$extension = pathinfo($_FILES ['file'] ["name"][$i], PATHINFO_EXTENSION);
array_push($fileNames,microtime_float().'_'.rand(1, 99999999).'.'.$extension);
if (move_uploaded_file( $_FILES ['file'] ["tmp_name"][$i], "../images/iduploads/".$fileNames[$i])) {
$result['error'] = false;
$result['message'] = 'Upload success';
} else {
$result['error'] = true;
$result['message'] = 'Something went wrong, try again';
throw new Exception('Could not move file');
}
} catch (Exception $e) {
$result['error'] = true;
$result['message'] = 'Error, photos did not upload, try again';
}
}
if(count ( $_FILES ['file'] ['name']) > 0 && !empty($fileNames))
$db->uploadIdentificationDocs($userfk, $fileNames[0], $fileNames[1], $fileNames[2]);
echo json_encode($result);
function microtime_float(){
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
?>
从我的Android端我使用
@POST("idUpload.php")
Call<Result> uploadMultiFile(@Body RequestBody file);
和
APIService service = retrofit.create(APIService.class);
MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);
User user = SharedPreferencesUtils.getUserPreferences(this);
builder.addFormDataPart("userid", user.getUserId());
builder.addFormDataPart("file[]", profilePicture.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), profilePicture));
MultipartBody requestBody = builder.build();
ProgressRequestBody progressRequestBody = new ProgressRequestBody(requestBody, this);
Call<Result> call = service.uploadMultiFilee(progressRequestBody);
这样可行但我不喜欢让Slim
上传图片的想法,因为我选择它是因为它的简单和干净的代码。这感觉不对,所以我尝试使用slims'
提供的功能上传
$app->post('/uploadprofilepicture/{userid}', function (Request $request, Response $response) {
$db = new Functions();
$userFk = $request->getAttribute('userid');
$result['error'] = true;
$result['message'] = 'Received here';
try {
$uploadedFiles = $request->getUploadedFiles();
if ($uploadedFile->getError() === UPLOAD_ERR_OK) {
$filename = moveUploadedFile($directory, $uploadedFile);
$result['error'] = true;
$result['message'] = 'Upload successs image '.$filename;
}
}catch (Exception $e) {
$result['error'] = true;
$result['message'] = 'Error occured: '.$e;
}
$response->getBody()->write((json_encode($result)));
});
但它失败了,它只是返回error 500
,在运行postman
Call to a member function getError() on null
之后意味着$request->getUploadedFiles()
为空
答案 0 :(得分:0)
应该是 $uploadedFiles
而不是$uploadedFile
。这就是你得到null的原因。
编辑:$uploadedFile
变量未初始化。这就是你得到null的原因。例如,如果html定义如下
<form method="post" enctype="multipart/form-data">
<input type="file" name="myUploadedFile">
</form>
然后在处理文件上传的代码中,它应该是
$uploadedFiles = $request->getUploadedFiles();
$uploadedFile = $uploadedFiles['myUploadedFile'];
if ($uploadedFile->getError() === UPLOAD_ERR_OK) {
//TODO: move file
}
答案 1 :(得分:0)
use Slim\Http\UploadedFile;
$profilePhotoContainer = $app->getContainer();
$profilePhotoContainer['upload_directory'] = '../images/iduploads/';
$app->post('/uploadprofilepicture', function (Request $request, Response $response) {
$db = new Functions();
$directory = $this->get('upload_directory');
$result['error'] = true;
$result['message'] = 'Received here';
try {
$uploadedFiles = $request->getUploadedFiles();
$uploadedFile = $uploadedFiles['profilephoto'];
if ($uploadedFile->getError() === UPLOAD_ERR_OK) {
$filename = moveUploadedFile($directory, $uploadedFile);
$result['error'] = true;
$result['message'] = 'Upload successs image '.$filename;
}
}catch (Exception $e) {
$result['error'] = true;
$result['message'] = 'Error occured: '.$e;
}
$response->getBody()->write((json_encode($result)));
});
function moveUploadedFile($directory, UploadedFile $uploadedFile){
$extension = pathinfo($uploadedFile->getClientFilename(), PATHINFO_EXTENSION);
$basename = bin2hex(random_bytes(8));
$filename = sprintf('%s.%0.8s', $basename, $extension);
$uploadedFile->moveTo($directory . DIRECTORY_SEPARATOR . $filename);
return $filename;
}