美文网首页
swift上传图片

swift上传图片

作者: zhangwenqiang | 来源:发表于2018-05-22 10:02 被阅读24次

OC翻译过来的swift写法,不过不太好用,最后用afnetwork实现的的图片上传
let queue = DispatchQueue(label: "com.brycegao.gcdtest", attributes: .concurrent)
queue.async(group: group) {

        let pUrl = URL.init(string: strUrl)
        if pUrl == nil {
            return
        }
        let request = NSMutableURLRequest.init(url: pUrl!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10)
        
        
        let boundary:String="AaB03x"
        let MPboundary = "--\(boundary)"
        let endMPboundary = "\(MPboundary)--"
        let body = NSMutableString.init()
        let imgData = UIImagePNGRepresentation(pImg)
        body.append("\(MPboundary)\r\n")
        body.append("Content-Disposition: form-data; name=\"\"; filename=\"image\"\r\n")
        body.append("Content-Type: image/jpge,image/gif, image/jpeg, image/pjpeg, image/pjpeg\r\n\r\n")
        let end="\r\n\(endMPboundary)"
        let myRequestData = NSMutableData.init()

        myRequestData.append(body.data(using: String.Encoding.utf8.rawValue)!)
        myRequestData.append(imgData!)
        myRequestData.append(end.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!)
        let content = "multipart/form-data; boundary=\(boundary)"
        request.setValue(content, forHTTPHeaderField: "Content-Type")
        request.setValue("\(myRequestData.length)", forHTTPHeaderField: "Content-Length")
        request.httpBody = myRequestData as Data
        request.httpMethod = "POST"
        let session = URLSession.shared
        
        //上传数据流
        
        let uploadTask = session.uploadTask(with: request as URLRequest as URLRequest, from: imgData) {
            (data:Data?, response:URLResponse?, error:Error?) -> Void in
            //上传完毕后
            if error != nil{
                print(error as Any)
            }else{
                let str = String(data: data!, encoding: String.Encoding.utf8)
                print("上传完毕:\(str ?? "")")
                let result = try?JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
                DispatchQueue.main.async {
                       if result is Dictionary<String, Any>
                       {
                           let pDic = result as! NSDictionary
                            success(pDic)
                       }else{
                        success(["data":result])
                    }
               }
            }
        }
        //使用resume方法启动任务
        uploadTask.resume()
    }

相关文章

网友评论

      本文标题:swift上传图片

      本文链接:https://www.haomeiwen.com/subject/jtfhjftx.html