我一直在我的應用程序中使用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