Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

ios - Upload image to server - Swift 3

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 {

My request is formed as below

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...