服务器的前端用的是nginx 后端是tocat,具体不知什么个原理没有接触,不过nginx是支持我这样上传的
1.代码类:
//
// JPCUploadHelper.swift
// joopic
//
// Created by jianxiong li on 16/4/9.
// Copyright © 2016年 joobot. All rights reserved.
//
import Foundation
protocol JPCUploadStatusDelegate{
func bytesSent(key:String,bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64);
func complete(key:String,error:NSError?,jesionStr:String?);
}
var upHelpers:NSMutableDictionary = NSMutableDictionary()
class JPCUploadHelper:NSObject{
var session:NSURLSession?
var delegate:JPCUploadStatusDelegate?
var key:String!
var backgroundCompletionHandler:(()->())?
private static let JPC_UPLOAD_IDENTIFIER_PRE:String = "IDENTIFIER_PRE"
let boundary = "AF0xKhTmLbOuNdArY"
class func uploadHelper(key:String)->JPCUploadHelper{
let identifier = "\(JPC_UPLOAD_IDENTIFIER_PRE)_\(key)"
let helper:JPCUploadHelper? = upHelpers.objectForKey(identifier) as? JPCUploadHelper
print("===============================uploadHelper.......helper:\(helper)")
if(helper == nil){
return JPCUploadHelper(key: key)
}else{
return helper!
}
}
class func hasUploadHelper(identifier:String)->JPCUploadHelper?{
let helper:JPCUploadHelper? = upHelpers.objectForKey(identifier) as? JPCUploadHelper
return helper
}
//指定构造器
private init(key:String){
super.init()
self.key = key
if(self.session == nil){
let identifier = self.getIdentifier(key)
let config = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(identifier)
//config.discretionary = true
config.allowsCellularAccess = SafeUtil.getBoolean(KEY_SAVE_IMAGE_ON_2G_3G_NET, delf: false)//是否允许使用蜂窝连接
//print("JPCDownloadHelper init.......config.allowsCellularAccess:\(config.allowsCellularAccess) config.discretionary:\(config.discretionary)")
self.session = NSURLSession(configuration: config, delegate: self, delegateQueue: nil)
upHelpers.setObject(self, forKey: identifier)
}
}
private func getRequest(url:NSURL)->NSMutableURLRequest{
let req = NSMutableURLRequest(URL: url)
//1 MARK: >必须加参数 时间戳和鉴权 已经省略
//req.setValue("Bearer \(base64String!)", forHTTPHeaderField: "Authorization")
req.HTTPMethod = "POST"
// Add the header info
req.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
return req
}
//这个方法可能改成中上传一个图片的方法,去掉参数midFilepath minFilePath
//->2 Uploading Body Content Using a Stream 使用uploadTaskWithStreamedRequest(request) 上传
func uploadFile(ObjectFilePath: String,MidFilePath: String,MinFilePath: String,var reqURL:NSURL?,delegate:JPCUploadStatusDelegate){
print("=======================================================================================&