swift之原生文件上传

最近,微信有个好友,是从上认识的。他说文件上传不会做,让我帮忙,反正闲的没事,就研究了一下。其实用OC是非常简单的事情,这里翻译成swift,供新学swift参考,也方便自己今后查阅-.-

upload.swift

import UIKit

//分界标识
let boundaryStr="--"
let boundaryID="haha"

//上传文件的方法
func uploadFileToHost(urlString:String,name:String,fileName:String,mimeType:String,paramters:String?,fileData:NSData, sucess :(NSData?)->Void, failure :(NSError?)->Void ){
    
    if urlString.isEmpty{
        print ("主地址不能为空")
        return
    }
    //固定拼接的第一部分
    let top=NSMutableString()
    top.appendFormat("%@%@\r\n", boundaryStr,boundaryID)
    top.appendFormat("Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", name,fileName)
    top.appendFormat("Content-Type: %s\r\n\r\n", mimeType)
    
    //固定拼接第三部分
    let buttom=NSMutableString()
    buttom.appendFormat("%@%@\r\n", boundaryStr,boundaryID)
    buttom.appendString("Content-Disposition: form-data; name=\"submit\"\r\n\r\n")
    buttom.appendString("Submit\r\n")
    buttom.appendFormat("%@%@--\r\n", boundaryStr,boundaryID)
    
    //拼接
    let fromData=NSMutableData()
    //非文件参数
    if (paramters != nil){
        fromData.appendData((paramters?.dataUsingEncoding(NSUTF8StringEncoding))!)
    }
    fromData.appendData(top.dataUsingEncoding(NSUTF8StringEncoding)!)
    fromData.appendData(fileData)
    fromData.appendData(buttom.dataUsingEncoding(NSUTF8StringEncoding)!)
    
    //可变请求
    let requset=NSMutableURLRequest(URL: NSURL(string: urlString)!)
    requset.HTTPBody=fromData
    requset.HTTPMethod="POST"
    requset.addValue(String(fromData.length), forHTTPHeaderField:"Content-Length")
    let contype=String(format: "multipart/form-data; boundary=haha", boundaryID)
    requset.setValue(contype, forHTTPHeaderField: "Content-Type")
    
    let session=NSURLSession.sharedSession()
    session.uploadTaskWithRequest(requset, fromData: nil) { (responseData, response, error) -> Void in
        if error==nil{
            sucess(responseData)
        }
        else{
            failure(error)
        }
    }.resume()
}

只有这一个方法,下面来看一下怎么用:
我在工程里有一张名为“1.png”的图片,直接调用这个方法就可以了,可以看到服务器返回上传成功,亲测可行~

ViewController.swift

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let path=NSBundle.mainBundle().pathForResource("1", ofType:"png")
        let data=NSData(contentsOfFile: path!)
        let host="http://games.kmbopai.com/Services/UserInfoService.asmx/UploadFile"
        
        uploadFileToHost(host, name: "media", fileName: "1.png", mimeType: "image/png", paramters: nil, fileData: data!, sucess: { (responseData) -> Void in
        
            let result=String(data: responseData!, encoding: NSUTF8StringEncoding)
            print(result)
        }){ (error) -> Void in
        }
    }
}

控制台打印如下信息:

**Optional("\r\n{\"status\": 1, \"msg\": \"****上传文件成功!****\", \"name\": \"1.png\", \"path\": \"/upload/201601/12/201601121237134502.png\", \"thumb\": \"/upload/201601/12/thumb_201601121237134502.png\", \"size\": 73053, \"ext\": \"png\"}")**
swift之原生文件上传_第1张图片

你可能感兴趣的:(swift之原生文件上传)