将图像上传到服务器 - Swift 3 [英] Upload image to server - Swift 3

查看:20
本文介绍了将图像上传到服务器 - Swift 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将图像作为参数与我的请求一起发送.我已经使用下面的代码来调用我的 POST 请求,但我不知道如何将图像附加到正文中.

I want to send an image as a parameter along with my request. I have used the code below to call my POST request but I don't know how to append image to the body.

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

I am getting the image through image picker as follows:

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 看到了这一点,但无法自己实现.我不想以 base 64 格式对其进行编码.请帮我解决这个问题.

I am new to Swift. I have seen this through multipart/form-data but unable to implement it myself. I do not want to encode it in base 64 format. Please help me in this.

推荐答案

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

I use the following structure for sending images:

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

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

")
        body.appendString(string: "(value)
")
    }

    body.appendString(string: "--(boundary)
")

    let mimetype = "image/jpg"

    let defFileName = "yourImageName.jpg"
        
    let imageData = UIImageJPEGRepresentation(yourImage, 1)

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

")
    body.append(imageData!)
    body.appendString(string: "
")

    body.appendString(string: "--(boundary)--
")

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

然后你必须在你的函数中创建主体,如下所示:

then you have to create body in your function like following:

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

这篇关于将图像上传到服务器 - Swift 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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