我一直在我的应用程序中使用Alamofire通过多部分表单上传请求上传图像。这是工作得很好,直到我实现JWT身份验证和用户登录系统到我的CakePHP 3 REST API以下this documentation.在此之前,它工作时,它是绝对好的。上传将是成功的,可以填充到我的数据库中,并且您将能够在服务器上看到图像文件(通过Filezilla)。这个图片上传系统在我成功实现了带有JWT身份验证的登录系统并刚刚设法解决这个问题之后便破产了。但是,我遇到的问题是上载请求是成功的,但是只有图像文件名正在我的数据库中填充,我无法在Filezilla的服务器上查看图像文件,这非常奇怪。任何人都可以指出我的方向是正确的,还是有人有过这个问题?它在我的控制台日志中取得成功,所以它应该在理论上起作用。使用Alamofire将图像上传到服务器
这里是我的银行代码:
import UIKit
import Foundation
import Alamofire
import SwiftyJSON
class UploadImageController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var selectedImage: UIImage?
override func viewDidLoad() {
super.viewDidLoad()
}
@IBOutlet weak var myImageView: UIImageView!
override func viewDidAppear(_ animated: Bool) {
if selectedImage == nil {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true)
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo: [String : Any]) {
guard let image = didFinishPickingMediaWithInfo[UIImagePickerControllerOriginalImage] as? UIImage else { return }
selectedImage = image
myImageView.image = image
self.dismiss(animated: true, completion: nil)
}
@IBAction func uploadButtonTapped(_ sender: UIButton) {
guard let image = myImageView.image else { return }
upload(image)
}
override func viewWillDisappear(_ animated: Bool) {
selectedImage = nil
myImageView.image = nil
}
func upload(_ image: UIImage) {
let parameters: [String: String] = [
"artist_id": "1"
]
let imageData = UIImageJPEGRepresentation(image, 1)!
Alamofire.upload(multipartFormData: { multipartFormData in
multipartFormData.append(imageData, withName: "upload", fileName: "upload.jpg", mimeType: "image/jpeg")
for (key, value) in parameters {
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
}
}, to: "http://178.62.107.243/api/posts",
method:.post,
headers: ["Authorization": "Bearer \(Request.shared.token!)",
"Accept": "application/json",
"Content-Type": "application/json"],
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
}
case .failure(let encodingError):
print(encodingError)
}
})
}
}
这是我的PHP代码:
<?php
namespace App\Controller\Api;
use App\Controller\Api\AppController;
use Cake\Log\Log;
class PostsController extends AppController
{
public $paginate = [
'page' => 1,
'limit' => 500,
'maxLimit' => 500,
'contain' => ['Artists']
];
public function add() {
$this->Crud->on('beforeSave', function(\Cake\Event\Event $event) {
if(!empty($this->request->data['upload']['name'])) {
$file = $this->request->data['upload'];
$ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
$arr_ext = ['jpg', 'png']; //set allowed extensions
$newFileName = time() . "_" . rand(000000, 999999);
//only process if the extension is valid
if (in_array($ext, $arr_ext)) {
//do the actual uploading of the file. First arg is the tmp name, second arg is
//where we are putting it
move_uploaded_file($file['tmp_name'], WWW_ROOT . 'img/posts/' . $newFileName . '.' . $ext);
//prepare the filename for database entry
$imageFileName = $newFileName;
$event->subject->entity->file_name = $imageFileName;
}
}
});
$this->Crud->execute();
}
}
这里是我在过去的20分钟之做(如果这甚至可以帮助上传请求):
我已经找出了问题所在。这是因为由UIImageJPEGRepresentation表示的图像数据需要为'0'。 像这样: let imageData = UIImageJPEGRepresentation(image,0)! 我不知道为什么,但它的工作原理!现在图像文件正在上传到我的服务器。如果有人知道价值需要为零的原因,请留下评论。 – Sebastian
将它设置为零(0)会最大化压缩,因此您的服务器上可能有文件大小限制? – rmp
@rmp哦对,谢谢你。我不知道这一点,我只是使用数字海洋账户......我会进一步阅读! – Sebastian