2017-06-01 89 views
0

我一直在我的應用程序中使用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分鐘之做(如果這甚至可以幫助上傳請求):

Database_posts table

+1

我已經找出了問題所在。這是因爲由UIImageJPEGRepresentation表示的圖像數據需要爲'0'。 像這樣: let imageData = UIImageJPEGRepresentation(image,0)! 我不知道爲什麼,但它的工作原理!現在圖像文件正在上傳到我的服務器。如果有人知道價值需要爲零的原因,請留下評論。 – Sebastian

+1

將它設置爲零(0)會最大化壓縮,因此您的服務器上可能有文件大小限制? – rmp

+0

@rmp哦對,謝謝你。我不知道這一點,我只是使用數字海洋賬戶......我會進一步閱讀! – Sebastian

回答

0

當我處理多形式,我喜歡檢查鍵/值,以便我可以以不同的方式處理圖像。我不知道這是不是你的問題。這裏是我通常如何對待它:

// append parameters to request 
for (key, value) in object { 
    if value != nil{ 
     //image data 
     if value!.isKind(of: UIImage.self){ 
      // convert image to data and append to request 
      if let imageData = UIImageJPEGRepresentation(value as! UIImage, 1) { 
       multipartFormData.append(imageData, withName: key, fileName: "image.png", mimeType: "image/png") 
      } 
     } 
     //non-image data 
     else{ 
      let stringValue = String(describing: value!) 
      if let formData = stringValue.data(using: String.Encoding.utf8, allowLossyConversion: false){ 
       multipartFormData.append(formData, withName: key) 
      } 
     } 
    } 
    else{ 
     //no data for key (nil), don't send property 
    } 
} 
+0

這不是問題。感謝您的提示,雖然:) – Sebastian

相關問題