2016-11-10 56 views
8

這是我的代碼,我想上傳圖像到服務器使用Alamofire,它不是錯誤,但它不能將圖像推送到服務器。我該怎麼辦 ?預先感謝。上傳圖像到服務器使用Alamofire

let url = URL(string: urlString)! 
    var urlRequest = URLRequest(url: url) 
    urlRequest.httpMethod = "POST" 

    let parameters = ["name": rname] 

    do { 
     urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: []) 
    } catch { 
     print(error) 
    } 

    urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") 
     let image = UIImage.init(named: "myImage") 
     let imgData = UIImageJPEGRepresentation(image!, 0.2)! 


    Alamofire.upload(multipartFormData: { MultipartFormData in 

      MultipartFormData.append(imgData, withName: "fileset", fileName: "name", mimeType: "image/jpg") 


     },with: urlRequest,encodingCompletion: { encodingResult in 

      switch encodingResult { 

      case .success(let upload, _, _): 

       upload.responseJSON { response in 

        if let info = response.result.value as? Dictionary<String, AnyObject> { 

         if let links = info["links"] as? Dictionary<String, AnyObject> { 

          if let imgLink = links["image_link"] as? String { 
           print("LINK: \(imgLink)") 
          } 
         } 
        } 

       } case .failure(let error): 
        print(error) 
      } 
     }) 

回答

25

試試下面的代碼

let image = UIImage.init(named: "myImage") 
let imgData = UIImageJPEGRepresentation(image!, 0.2)! 

let parameters = ["name": rname] 

Alamofire.upload(multipartFormData: { multipartFormData in 
     multipartFormData.append(imgData, withName: "fileset",fileName: "file.jpg", mimeType: "image/jpg") 
     for (key, value) in parameters { 
       multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key) 
      } 
    }, 
to:"mysite/upload.php") 
{ (result) in 
    switch result { 
    case .success(let upload, _, _): 

     upload.uploadProgress(closure: { (progress) in 
      print("Upload Progress: \(progress.fractionCompleted)") 
     }) 

     upload.responseJSON { response in 
      print(response.result.value) 
     } 

    case .failure(let encodingError): 
     print(encodingError) 
    } 
} 
+1

什麼是'rname'這裏?在'let參數= [「name」:rname]' –

+0

不知道rname來自哪裏。然而,看起來這個答案和教程非常相似[這裏](https://www.raywenderlich.com/147086/alamofire-tutorial-getting-started-2) –

+1

@JeffMuir本教程不包括這個 – iosMentalist

5
let params: Parameters = ["name": "abcd" "gender": "Male"] 
Alamofire.upload(multipartFormData: 
    { 
     (multipartFormData) in 
     multipartFormData.append(UIImageJPEGRepresentation(self.yourimageView.image!, 0.1)!, withName: "image", fileName: "file.jpeg", mimeType: "image/jpeg") 
     for (key, value) in params 
     { 
      multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key) 
     } 
}, to:yourUrl,headers:nil) 
{ (result) in 
    switch result { 
    case .success(let upload,_,_): 
     upload.uploadProgress(closure: { (progress) in 
      //Print progress 
     }) 
     upload.responseJSON 
      { response in 
       //print response.result 
       if response.result.value != nil 
       { 
        let dict :NSDictionary = response.result.value! as! NSDictionary 
        let status = dict.value(forKey: "status")as! String 
        if status=="1" 
        { 
         print("DATA UPLOAD SUCCESSFULLY") 
        } 
       } 
     }     
    case .failure(let encodingError): 
     break 
    } 
} 
+0

你的答案在沒有任何解釋的情況下會有用嗎? – Shashanth

+0

只要確保參數中的所有值都是字符串,就會導致崩潰。 –

+0

所以如果我有webservice的參數名稱是徽標 我應該在哪裏替換它 withName:「image」。 或 文件名:「file.jpeg」 –

2

需要指定name, fileName, mimeType,這些都是很重要的多臺服務器

func upload(image: UIImage, completion: (URL?) -> Void) { 
    guard let data = UIImageJPEGRepresentation(image, 0.9) else { 
     return 
    } 

    Alamofire.upload(multipartFormData: { (form) in 
     form.append(data, withName: "file", fileName: "file.jpg", mimeType: "image/jpg") 
    }, to: "https://yourawesomebackend.com", encodingCompletion: { result in 
     switch result { 
     case .success(let upload, _, _): 
     upload.responseString { response in 
      print(response.value) 
     } 
     case .failure(let encodingError): 
     print(encodingError) 
     } 
    }) 
    }