简体   繁体   English

Swift 4-Alamofire 4使用参数上传图片

[英]Swift 4 - Alamofire 4 Upload Image with Parameter

I know there's so many tutorials or questions about this. 我知道有很多关于此的教程或问题。 I've tried that all but I have no luck for this. 我已经尝试了所有方法,但是对此我没有运气。

I need to get upload progress from Alamofire . 我需要从Alamofire获取上传进度。 Here's my code: 这是我的代码:

func uploadpp(data1: Array<Any>, data2: Data?){
    guard let url = URL(string: "\(API.storage)/upload/profile/picture?format=json") else {
        return
    }

    let parameters: Parameters = [
        "crop": [],
        "folder_type": "1",
        "folderid": "0",
        "image_byte": data1,
        "image_url": "",
        "partnerid": "\(memberid)",
        "partneruserid": "0",
        "publicip": "",
        "sourceid": "4"
    ]

    let headers: HTTPHeaders = [
        "Authorization": API.basicstring,
        "Content-type": "multipart/form-data"
    ]

    Alamofire.upload(multipartFormData: { (multipartFormData) in
        if let data = data2 {
            multipartFormData.append(data, withName: "image", fileName: "image.jpeg", mimeType: "image/jpeg")
        }

        for (key, value) in parameters {
            multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key)
        }
    }, usingThreshold: UInt64.init(), to: url, method: .post, headers: headers) { (result) in
        switch result {
        case .success(let upload, _, _):
            upload.uploadProgress(closure: { (progress) in
                print("proses", progress.fractionCompleted)
            })

            upload.responseJSON { response in
                print("Succesfully uploaded")
                if let err = response.error {
                    print("upload:", err)
                    return
                }

                if let s = response.result.value {
                    print("result:", s)
                    return
                }
            }
        case .failure(let error):
            print("Error in upload: \(error.localizedDescription)")
        }
    }
}

data1 is a byte array of image. data1是图像的字节数组。 I need this because my API have to read this type. 我需要这个,因为我的API必须读取这种类型。 And data2 is result of UIImageJPEGRepresentation(img, 0.5) . data2UIImageJPEGRepresentation(img, 0.5)

Then when I tried this, it printed Successfully uploaded but then gave me error: 然后,当我尝试此操作时,它打印Successfully uploaded但给我错误:

responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(error: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 3." UserInfo={NSDebugDescription=Invalid value around character 3.})) responseSerializationFailed(原因:Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(错误:Error Domain = NSCocoaErrorDomain代码= 3840“字符3无效值。” UserInfo = {NSDebugDescription =字符3无效值)})

As I know, this error appears when you make mistake on your url, parameters, or headers (CMIIW please). 据我所知,当您在网址,参数或标题(请输入CMIIW)上输入错误时,会出现此错误。

But I've tried to put this to Alamofire.request so here's my another code: 但是我尝试将其放入Alamofire.request所以这是我的另一个代码:

func uploadpp(data: Array<Any>){
    guard let url = URL(string: "\(API.storage)/upload/profile/picture?format=json") else {
        return
    }

    let parameters: Parameters = [
        "crop": [],
        "folder_type": "1",
        "folderid": "0",
        "image_byte": data,
        "image_url": "",
        "partnerid": "\(memberid)",
        "partneruserid": "0",
        "publicip": "",
        "sourceid": "4"
    ]

    let headers: HTTPHeaders = [
        "Authorization": API.basicstring,
        "Accept": "application/json"
    ]

    let req = Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers)
    req.downloadProgress { progress in
        print("lalala", Float(req.progress.fractionCompleted), progress.completedUnitCount)
    }

    req.responseJSON { response in
        if response.result.isSuccess {
            _ = self.getdata(json: JSON(response.result.value!))
            print(response.result.value!)
        }
        else {
            print("upload:", response.result.error!)
        }
    }
}

It was succesful but didn't give me the progress. 成功了,但是没有给我进展。 It just gave "1.0". 它只是给了“ 1.0”。

Maybe I confused about usage of Alamofire.request and Alamofire.upload , or somewhere from this all. 也许我对Alamofire.requestAlamofire.upload用法感到困惑,或者对此感到困惑。 So please somebody help me with this. 因此,请有人帮助我。

Thanks in advance. 提前致谢。

You can use MultipartFormData to for this case, Try this 您可以在这种情况下使用MultipartFormData来尝试

let parameters = [
            "station_id" :        "1000",
            "title":      "Murat Akdeniz",
            "body":        "xxxxxx"]

let imgData = UIImageJPEGRepresentation(UIImage(named: "1.png")!,1)



    Alamofire.upload(
        multipartFormData: { MultipartFormData in
        //    multipartFormData.append(imageData, withName: "user", fileName: "user.jpg", mimeType: "image/jpeg")

            for (key, value) in parameters {
                MultipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
            }

        MultipartFormData.append(UIImageJPEGRepresentation(UIImage(named: "1.png")!, 1)!, withName: "photos[1]", fileName: "swift_file.jpeg", mimeType: "image/jpeg")
        MultipartFormData.append(UIImageJPEGRepresentation(UIImage(named: "1.png")!, 1)!, withName: "photos[2]", fileName: "swift_file.jpeg", mimeType: "image/jpeg")


    }, to: "http://url") { (result) in

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

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

        case .failure(let encodingError): break
            print(encodingError)
        }


    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM