Skip to content

Instantly share code, notes, and snippets.

@bantic
Created December 9, 2017 19:10
Show Gist options
  • Save bantic/d8e39ba58e6efe34a0e1a7c4769c65e6 to your computer and use it in GitHub Desktop.
Save bantic/d8e39ba58e6efe34a0e1a7c4769c65e6 to your computer and use it in GitHub Desktop.
upload UIImage to server with swift
func saveImage(image: UIImage, name:String) {
let req = NSMutableURLRequest(url: NSURL(string:"http://127.0.0.1:3001/")! as URL)
let ses = URLSession.shared
req.httpMethod="POST"
req.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type")
req.setValue(name, forHTTPHeaderField: "X-FileName")
let jpgData = UIImageJPEGRepresentation(image, 1.0)
req.httpBodyStream = InputStream(data: jpgData!)
let task = ses.uploadTask(withStreamedRequest: req as URLRequest)
task.resume()
}
@bantic
Copy link
Author

bantic commented Dec 9, 2017

This is a modification of some Swift code that originally came from here: http://www.beardedhacker.com/blog/2016/08/31/streamed-upload-example-with-swift-and-node-dot-js/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment