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.