【问题标题】:Swift 4: How to post a file in params with Alamofire?Swift 4:如何使用 Alamofire 在参数中发布文件?
【发布时间】:2018-10-30 09:12:15
【问题描述】:

enter image description here

图片是我如何将文件上传到后端 API 的 Postman 示例。我正在努力如何使用 Alamofire 上传文件或 image.png/jpg?因为我无法在 Param 中包含该文件。

【问题讨论】:

  • 借助multipart,可以发送文件/图片。

标签: file upload swift4 alamofire


【解决方案1】:

试试这个代码

let image = UIImage.init(named: "myImage")
let imgData = UIImageJPEGRepresentation(image!, 0.2)!

let parameters = ["custid": 1] //Optional for extra parameter

Alamofire.upload(multipartFormData: { multipartFormData in
        multipartFormData.append(imgData, withName: "fileset",fileName: "file.jpg", mimeType: "image/jpg")
        for (key, value) in parameters {
                multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
            } //Optional for extra parameters
    },
to:"mysite/upload.php")
{ (result) in
    switch result {
    case .success(let upload, _, _):

        upload.uploadProgress(closure: { (progress) in
            print("Upload Progress: \(progress.fractionCompleted)")
        })

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

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

【讨论】:

    猜你喜欢
    • 2018-10-10
    • 1970-01-01
    • 2019-01-14
    • 2020-11-09
    • 2018-06-27
    • 2018-12-18
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    相关资源
    最近更新 更多