Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.