如何使用此数据上传multipart

时间:2017-09-26 10:24:32

标签: ios swift image multipartform-data multipart

我想以multipart的形式将此数据发送到带有图像/视频的服务器。我有字节数据形式的图像/视频数据(NSData或数据)

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

2 个答案:

答案 0 :(得分:0)

我使用Alamofire为Multipart Upload创建了一个函数。

调用此函数传递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")

希望有所帮助:)

答案 1 :(得分: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)
        }

        }
    }