0

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

  func myImageUploadRequest()
    {
        let headers = [
            "content-type": "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
            "cache-control": "no-cache"
        ]
        let parameters = [
            [
                "name": "Name",
                "value": "Swift"
            ],
            [
                "name": "Key",
                "fileName": "123.png"
//UIImagePNGRepresentation(myImageView.image!)

            ]
        ]

        let boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW"

        var body = ""
        var error: NSError? = nil
        do{
        for param in parameters {
            let paramName = param["name"]!
            body += "--\(boundary)\r\n"
            body += "Content-Disposition:form-data; name=\"\(paramName)\""
            if let filename = param["fileName"] {
                let contentType = param["content-type"]!
                let fileContent = try String(contentsOfFile: filename as! String, encoding: String.Encoding.utf8)
                if (error != nil) {
                    print(error)
                }
                body += "; filename=\"\(filename)\"\r\n"
                body += "Content-Type: \(contentType)\r\n\r\n"
                body += fileContent
            } else if let paramValue = param["value"] {
                body += "\r\n\r\n\(paramValue)"
            }
        }
       // }//do


        let request = NSMutableURLRequest(url: NSURL(string: "http://——----docUpload/MediaUpload/")! as URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)
        request.httpMethod = "PUT"
        request.allHTTPHeaderFields = headers
      //  request.httpBody = postData as Data
        let session = URLSession.shared
        let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
            if (error != nil) {
                print(error)
            } else {
                let httpResponse = response as? HTTPURLResponse
                print(httpResponse)
            }
        })

        dataTask.resume()
    }

        catch {
        } //new

}

I have seen many examples and tried but unable to implement it myself. please check my code and help me in this.

1 Answers1

0

One option is to encode the image in Base64, which you can then include as a string in your json. Although this answer refers to javascript, it explains the pluses and minuses of this approach in general.

For syntax check this answer, which lays out all possible options you might need, but the code below should provide you with the file content that you can add to the body of your request.

if let image = UIImage(named:"imageNameHere"), 
    let imageData = UIImagePNGRepresentation(image) {

    let fileContent = imageData.base64EncodedString(options: .lineLength64Characters)
}
Blake
  • 122
  • 1
  • 7