小编典典

将图像上传到服务器-Swift 3

swift

我想随请求一起发送图像作为参数。我使用下面的代码调用POST请求,但是我不知道如何将图像追加到正文中。

我通过图像选择器获取图像,如下所示:

if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {

我的要求如下

var request = URLRequest(url: URL(string: "")!) // link removed
        request.httpMethod = "POST"
        let postString = "user_id=\(userId)&image=\(image)"
        request.httpBody = postString.data(using:.utf8)

        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {               // check for fundamental networking error
                return
            }
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? AnyObject

                if let parseJSON = json {
                    print("resp :\(parseJSON)")
                }
            } catch let error as NSError {
                print("error : \(error)")
            }
        }
        task.resume()

我是Swift的新手。我已经通过multipart / form-data看到了这一点,但无法自己实现。我不想将其编码为基本64格式。请帮助我。


阅读 269

收藏
2020-07-07

共1个答案

小编典典

我使用以下结构发送图像:

func createRequestBodyWith(parameters:[String:NSObject], filePathKey:String, boundary:String) -> NSData{

    let body = NSMutableData()

    for (key, value) in parameters {
        body.appendString(string: "--\(boundary)\r\n")
        body.appendString(string: "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
        body.appendString(string: "\(value)\r\n")
    }

    body.appendString(string: "--\(boundary)\r\n")

    var mimetype = "image/jpg"

    let defFileName = "yourImageName.jpg"

    let imageData = UIImageJPEGRepresentation(yourImage, 1)

    body.appendString(string: "Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(defFileName)\"\r\n")
    body.appendString(string: "Content-Type: \(mimetype)\r\n\r\n")
    body.append(imageData!)
    body.appendString(string: "\r\n")

    body.appendString(string: "--\(boundary)--\r\n")

    return body
}



func generateBoundaryString() -> String {
    return "Boundary-\(NSUUID().uuidString)"
}



extension NSMutableData {

func appendString(string: String) {
    let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
    append(data!)
}

然后在函数中创建如下主体:

request.httpBody = self.createRequestBodyWith(parameters:yourParamsDictionary, filePathKey:yourKey, boundary:self.generateBoundaryString)
2020-07-07