简体   繁体   中英

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 . 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. 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(reason: Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(error: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 3." UserInfo={NSDebugDescription=Invalid value around character 3.}))

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

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

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

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

Thanks in advance.

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


    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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