【问题标题】:How to upload multipart with this data如何使用此数据上传分段
【发布时间】:2018-03-07 12:36:26
【问题描述】:

我想以多部分的形式将此数据与图像/视频一起发送到服务器。我有字节数据形式(NSData 或 Data)的图像/视频数据

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

【问题讨论】:

标签: ios swift image multipartform-data multipart


【解决方案1】:
 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)
        }

        }
    }

【讨论】:

    【解决方案2】:

    我已经使用 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")
    

    希望对你有帮助:)

    【讨论】:

    • 如何使用此功能发送视频?
    猜你喜欢
    • 2018-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-08
    • 2015-02-04
    • 1970-01-01
    • 2013-03-13
    相关资源
    最近更新 更多