2017-09-26 92 views
0

我想以multipart的形式將此數據發送到帶有圖像/視頻的服務器。我有字節數據形式的圖像/視頻數據(NSData或Data)如何使用此數據上傳多部分

{"mediauploadata": 
    { 
"type":"poll", 
"server_token":"03f0e635b4c01b9f398de393259de8650b54c85c24f49998af50593643f559230d95e8e605612653769f4871b543e25d48bf", 
"id":"105" 
    } 
} 
+0

[上傳圖像的可能的複製與斯威夫特參數](https://stackoverflow.com/questions/26162616/upload-image-with-parameters-in-swift) – Jaydeep

+0

你可以用alamofire –

回答

0

我已經使用Alamofire創建了用於分段上傳的函數。

調用此函數傳遞Web服務URL,參數和圖像。

func WSPostAPIMultiPart(_ aStrULR:String, 
         param: [String: Any], 
         image : UIImage?, 
         controller: UIViewController, 
         successBlock: @escaping (_ response:[String : Any]?) -> Void, 
         failureBlock: @escaping (_ error: Error?) -> Void) { 

    var dictHeaders : HTTPHeaders = [String : String]() 

    if (Alamofire.NetworkReachabilityManager()?.isReachable)!{ 
    Alamofire.upload(
     multipartFormData: { MultipartFormData in 

      let JSONData: Data? = try? JSONSerialization.data(withJSONObject: param, options: .prettyPrinted) 
      MultipartFormData.append(JSONData!, withName: "json") 
      if image != nil{ 
       MultipartFormData.append(UIImageJPEGRepresentation(image!, 0.5)!, withName: "profile_image",fileName: "image.jpeg", mimeType: "image/jpeg") 
       // withName : You will pass the key name required by your server 
      } 

    }, to: aStrULR ,method : .post , headers : dictHeaders) { (result) in 

     switch result { 
     case .success(let upload, _, _): 

      upload.responseJSON { response in 

       if let value = response.result.value { 
        let dictResponse = JSON(value).dictionaryObject 

        successBlock(dictResponse) 
       } 
      } 

     case .failure(let error): 
      failureBlock(error) 
     } 
    } 
    }else{ 
     print("NO INTERNET CONNECTIVITY") 
    } 
} 

對於視頻:只是通過videoURL一個額外的參數和附加:

MultipartFormData.append(videoUrl, withName: "profileVideo", fileName: "video.mp4", mimeType: "video/mp4") 

希望它能幫助:)

+0

如何發送vi用這個函數deo? –

+0

我已經更新了我的答案。 –

0
func uploadDataWith(parameter params:Dictionary<String,String>,data:Data?,isImage:Bool,handler:@escaping ((Dictionary<String,Any>?) -> Void)) { 
     Alamofire.upload(multipartFormData: { (multipartFormData) in 
     for (key, value) in params { 
      multipartFormData.append(value.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: key) 
     } 
     if data != nil && isImage { 
       multipartFormData.append(data, withName: "photo_upload", fileName: "file.png", mimeType: "image/png")  
     } 
     if data != nil && !isImage { 
      multipartFormData.append(data, withName: "video_upload", fileName: "file.mp4", mimeType: "video/mp4")  
     } 
     }, to: "http://") { (encodingResult) in 
     switch encodingResult { 
     case .success(let upload, _, _): 
      upload.responseJSON { response in 
       switch response.result { 
       case .success: 
        if let jsonDict = response.result.value as? Dictionary<String,Any> { 
         print("Json Response: \(jsonDict)") 
         handler(jsonDict) 
         print(jsonDict,(response.response!.statusCode)) 
        } 
        else{ 
         print(response.response!.statusCode) 
         handler(nil) 
        } 
        if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) { 
         print("Server Response: \(utf8Text)") // original server data as UTF8 string 
        } 
        break 
       case .failure(let error): 
        print(response.response!.statusCode) 
        print_debug(error) 
        handler(nil) 
        break 
       } 
      } 
     case .failure(let encodingError): 
      print(encodingError) 
     } 

     } 
    } 
相關問題