我正在尝试将文件上传到服务器。我在我的后端代码中使用SlimFramework和PHP,它是RESTful形式。如果我通过邮递员上传图像上传效果非常好但是我无法使用Swift和Alamofire库将其上传。
在我在后端的路线中,我从body参数:
获得这样的文件 $image = $request->getUploadedFiles();
并上传我使用:
$image->moveTo("myPath");
在Swift中我有路由器,它提供了.post
方法和路由URL,我试过这样:
func uploadImage(user_id: Int, image: Data, completion: @escaping (_ error: Error?, _ success: Bool)->Void) {
let parameters = [
"user_id": user_id,
"newFile": image
] as [String : Any]
Alamofire.request(Router.imageUplaod(parameters: parameters))
.validate(statusCode: 200..<300)
.responseJSON { response in
switch response.result{
case .failure(let error):
completion(error, false)
print(error)
case .success(let value):
//Registered sucesfully! let json = JSON(value)
completion(nil, true)
}//Switch case
}//Alamofire
}
我称之为:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let chosenProfileImage = info[UIImagePickerControllerEditedImage] as! UIImage
let imageData = UIImageJPEGRepresentation(chosenProfileImage, 0.2)
profileImageView.image = chosenProfileImage
dismiss(animated: true) {
API.uploadImage(user_id: User.sharedInstance.user_id, image: imageData!) { (error, success) in
if success{
print("IMAGE UPLOADDED")
}
}
}
}
这是我的后端路线:
$this->post('/image/upload', function($request, $response, $args){
global $database;
$data = $request->getParsedBody();
$user_id = $data['user_id'];
$files = $request->getUploadedFiles();
if (empty($files['newfile'])) {
throw new Exception('Expected a newfile');
}
$newfile = $files['newfile'];
if ($newfile->getError() === UPLOAD_ERR_OK) {
$uploadFileName = "profileImage".$user_id.".jpg";
$newfile->moveTo("/path/to/image/$uploadFileName");
}
$database->query("UPDATE `users` SET `profile_image_url` = :image WHERE user_id = :user_id");
$database->bind(':image', $uploadFileName);
$database->bind(':user_id', $user_id);
$database->execute();
$Jsonarray['status'] = "true";
$Jsonarray['message'] = "Image Uploaded Successfully";
return $response->withStatus(200)->withHeader('Content-Type', 'application/json')->write(json_encode($Jsonarray));
});
奇怪的是,Alamofire输出状态代码500但服务器并没有告诉我任何相关信息。问题必须出在Swift部分。所以我甚至不知道如何调试它。
我该如何解决这个问题?
答案 0 :(得分:9)
我解决了这个问题。我用那种方式重建了它:
所以在Swift中我将它转换成这样:
let chosenProfileImage = info[UIImagePickerControllerEditedImage] as! UIImage
let imageData = UIImageJPEGRepresentation(chosenProfileImage, 0.2)
profileImageView.image = chosenProfileImage
let base64String = imageData?.base64EncodedString(options: .lineLength64Characters)
后端几乎相同,只是使用base64_decode();
将其转换回文件并使用file_put_contents();
函数将其移动到服务器。