我正在尝试将文件上传到服务器.我在后端代码中使用SlimFramework和
PHP,它采用REST形式.如果我通过邮递员上传图片上传功能非常好,但是我无法使用Swift和Alamofire库进行上传.
在我后端的路由,我得到这样的文件,从body参数:
$image = $request-> getUploadedFiles();
并上传我使用:
$图像 – >的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部分.所以我甚至不知道如何调试它.
我该如何解决问题?
我解决了这个问题.我这样重建:
原文链接:https://www.f2er.com/php/131941.html>将图像转换为客户端上的Base64 String
>将其解码为后端图像
>上传它
所以在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();功能将其移动到服务器.