ios swift 4 - 带有UIimage文件的Alamofire post参数(将curl转换为alamofire)

问题描述 投票:0回答:1

我想发送.post请求上传图片。请求的基础是这cURL

curl -X POST \
    --header "Authorization: 123456..." \
    --header "X-Storage-Id: 123456..." \
    --form fileItems[0].fileToUpload=@"/path/to/file1.txt"  \
    --form fileItems[0].path="/path1/path2/"    \
    --form fileItems[0].replacing=true  \
    --form fileItems[1].fileToUpload=@"/path/to/file2.txt"  \
    --form fileItems[1].path="/path1/path3/"    \
    --form fileItems[1].replacing=true  \
    http://example.com/uploadfiles

我有UIImage来自:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

        picker.dismiss(animated: true, completion: nil)

        let image = info[UIImagePickerControllerEditedImage] as! UIImage


        // image  <------- i have this uiimage for uploading

    }

如何通过Alamofire上传cazL上传image (UIImage)

ios swift alamofire
1个回答
3
投票
let data = UIImagePNGRepresentation(image)!

let headers = ["Authorization": "...", 
               "X-Storage-Id": "..."]

let parameters = ["fileItems[0].replacing": "true",
                  "fileItems[0].path": "/path/something"]

Alamofire.upload(multipartFormData: { form in

    form.append(data,
                withName: "fileItems[0]",
                fileName: "file1.png",
                mimeType: "image/png")

    parameters.forEach({
        form.append($0.value.data(using: .utf8)!, withName: $0.key)
    })

}, to: "https://example.com/uploadfiles", method: .post, headers: headers) { result in

    //switch result { ... }

}
© www.soinside.com 2019 - 2024. All rights reserved.