Skip to content

Instantly share code, notes, and snippets.

@samuelbeek
Last active November 10, 2015 11:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samuelbeek/8578c4a52ea3dc875305 to your computer and use it in GitHub Desktop.
Save samuelbeek/8578c4a52ea3dc875305 to your computer and use it in GitHub Desktop.
Upload a file in a Multipart form
struct Uploader {
static let baseUrl = "YOUR API URL"
static func multipartBody(filePathKey: String, imageDataKey: NSData, boundary: String) -> NSData {
let body = NSMutableData();
let filename = "user-profile.jpg"
let mimetype = "image/jpg"
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(filePathKey)\"; filename=\"\(filename)\"\r\n")
body.appendString("Content-Type: \(mimetype)\r\n\r\n")
body.appendData(imageDataKey)
body.appendString("\r\n")
body.appendString("--\(boundary)--\r\n")
return body
}
static func upload(image: UIImage, callback: Result<String> -> ()) {
let imageData = UIImageJPEGRepresentation(image, 10)
let url = NSURL(string: "\(baseUrl)/helpers/upload")!
let request = NSMutableURLRequest(URL:url);
request.HTTPMethod = "POST";
let boundary = "Boundary-\(NSUUID().UUIDString)"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
if(imageData==nil) { return; }
request.HTTPBody = self.multipartBody("image", imageDataKey: imageData!, boundary: boundary)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
callback(.Error(SMBError(code: 0, message: "something went wrong: \(error)")))
return
}
if let data = data{
if let imgUrl = JSON(data: data)["img_url"].string {
callback(.Value(imgUrl))
} else {
callback(.Error(SMBError(code: 0, message: "something went wrong: url not found")))
}
}
}
task.resume()
}
}
enum Result<A> {
case Error(SMBError)
case Value(A)
}
/// Very simple error type.
struct SMBError {
/// Error code
let code : Int
/// Message
let message : String
/// Printable message for the logs.
var debugMessage : String {
return "an error occured with code: \(code), message: \(message)"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment