2016-11-30 26 views
0

我要上傳圖片到後端(PHP),我必須與參數名發送:「圖片報」斯威夫特3上傳圖片的問題(格式)

func uploadImage(token: String, userID: Int, imgStr: String, 
       successBlock: @escaping (JSON, Int) ->(), 
       failureBlock: @escaping (String) ->()) 
{ 
    let params: [String: Any] = [ 
     "picture" : imgStr 
    ]   

    Alamofire.request( "\(API_URL)" + "users/\(userID)", 
     method: .put, 
     parameters: params, 
     encoding: JSONEncoding.default, 
     headers: Headers().withToken(token: token)).responseJSON 
     { response in 

      print(response) 
      print(response.result) 
      print(response.request) 
      print(response.response) 

      response.result.error != nil 
       ? (failureBlock(response.result.error!.localizedDescription)) 
       : (successBlock(JSON(response.result.value), 
           (response.response?.statusCode)!)) 
    } 
} 

但是我收到此消息

JSON: { 
    "picture" : [ 
    "The picture must be a file of type: jpeg, jpg, png." 
    ] 
} 

有辦法將UIImage轉換爲字符串與png/jpeg格式?

非常感謝!

+0

在服務器端被他們期待圖像爲base64字符串格式或文件格式? – Rajat

+0

@Rajat他們期待的文件格式(表格數據?) –

+1

但你發送圖像作爲字符串 – Rajat

回答

1

這是如何您可以發送圖像服務器與文件格式

let headers: HTTPHeaders = [String:String] 
let URL = try! URLRequest(url: yourURL, method: .put, headers: headers) 

Alamofire.upload(multipartFormData: { multipartFormData in 
    if let _image = UIImage(named:"") { 
     if let imageData = UIImagePNGRepresentation(_image) { 
      multipartFormData.append(imageData, withName: "signImg", fileName: "picture.png", mimeType: "image/png") 
     } 
    } 
    }, with: URL, encodingCompletion: { 
     encodingResult in 
     switch encodingResult { 
     case .success(let upload, _, _): 
      upload.responseJSON { response in 
       debugPrint("SUCCESS RESPONSE: \(response)") 
      } 
     case .failure(let encodingError): 
      // hide progressbas here 
      print("ERROR RESPONSE: \(encodingError)") 
     } 
}) 
+0

是否有可能做同樣的事情頭部? –

+0

我得到了這個消息:模糊引用成員'上傳(_to:方法:標題:)' –

+0

@KevinSabbe更新答案與標題 – Rajat