Swift 4-Alamofire 4使用参数上传图片 [英] Swift 4 - Alamofire 4 Upload Image with Parameter

查看:152
本文介绍了Swift 4-Alamofire 4使用参数上传图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道关于此的教程或问题太多。我已经尝试了所有方法,但是我对此没有运气。

I know there's so many tutorials or questions about this. I've tried that all but I have no luck for this.

我需要从 Alamofire 获取上传进度。这是我的代码:

I need to get upload progress from 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 是图像的字节数组。我需要这个,因为我的API必须读取这种类型。而 data2 UIImageJPEGRepresentation(img,0.5)的结果。

data1 is a byte array of image. I need this because my API have to read this type. And data2 is result of UIImageJPEGRepresentation(img, 0.5).

然后,当我尝试此操作时,它会打印成功上传,但随后出现错误:

Then when I tried this, it printed Successfully uploaded but then gave me error:


responseSerializationFailed(原因:Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(错误:Error Domain = NSCocoaErrorDomain代码= 3840字符3周围的值无效。 UserInfo = {NSDebugDescription =字符3周围的值无效。}))

responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(error: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 3." UserInfo={NSDebugDescription=Invalid value around character 3.}))

据我所知,当您对网址,参数或标头(请使用CMIIW)。

As I know, this error appears when you make mistake on your url, parameters, or headers (CMIIW please).

但是我尝试将其放入 Alamofire.request ,所以这是我的另一个代码:

But I've tried to put this to Alamofire.request so here's my another code:

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!)
        }
    }
}

成功,但是没有给我进展。它只是给出了 1.0。

It was succesful but didn't give me the progress. It just gave "1.0".

也许我对 Alamofire.request Alamofire.upload 或所有其他内容。因此,请有人帮我解决这个问题。

Maybe I confused about usage of Alamofire.request and Alamofire.upload, or somewhere from this all. So please somebody help me with this.

预先感谢。

推荐答案

在这种情况下,您可以使用 MultipartFormData 来尝试

You can use MultipartFormData to for this case, Try this

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)
        }


    }

这篇关于Swift 4-Alamofire 4使用参数上传图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆