Skip to content

Instantly share code, notes, and snippets.

@jiaozhu
Created December 4, 2015 05:41
Show Gist options
  • Save jiaozhu/dd732d7caf574e02d986 to your computer and use it in GitHub Desktop.
Save jiaozhu/dd732d7caf574e02d986 to your computer and use it in GitHub Desktop.
Upload images to Qiniu via multipart-form with Alamofire
//
// QNUploader.swift
//
// Created by Lex on 12/1/15.
//
import Foundation
import Alamofire
private let kCDNDomain = "__YOUR_QINIU_CDN_DOMAIN__"
private let kUploadDomain = "http://upload.qiniu.com/"
typealias QNUploadCompletion = ((URL: NSURL?) -> Void)
struct QNUploader {
func uploadImage(image: UIImage, token: String, completion: QNUploadCompletion?) {
guard let data = UIImageJPEGRepresentation(image, 0.7) else {
completion?(URL: nil)
return
}
Alamofire.upload(.POST, kUploadDomain, multipartFormData: {
form in
form.appendBodyPart(data: data, name: "file")
form.appendBodyPart(
data: token.dataUsingEncoding(NSUTF8StringEncoding)!,
name: "token")
}) { result in
switch result {
case .Success(let upload, _, _):
upload.responseJSON { response in
if let key = response.result.value?["key"] as? String {
let URLString = "http://\(kCDNDomain)/\(key)"
let URL = NSURL(string: URLString)
completion?(URL: URL)
} else {
completion?(URL: nil)
}
}
default:
completion?(URL: nil)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment