text Alamofire - 使用Swift 3上传文件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了text Alamofire - 使用Swift 3上传文件相关的知识,希望对你有一定的参考价值。

    func mimeType(fileUrl: URL) -> String? {
        // get a mime type for an extension using MobileCoreServices.framework
        if let pathExtension = fileUrl.pathExtension as CFString? {
            if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, nil)?.takeRetainedValue() {
                if let mimetype = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() {
                    return mimetype as String
                }
            }
        }
        return "application/octet-stream"
    }
    func isMimeTypeImage(fileUrl: URL) -> Bool {
        //  Check File Is image or Not    Finally, put this UTI to good use:
        if let pathExtension = fileUrl.pathExtension as CFString? {
            if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, nil)?.takeRetainedValue() {
                if UTTypeConformsTo(uti, kUTTypeImage) {
                    return true
                }
            }
        }
        return false
    }
    
    
    // File Upload Code
    func apiUploadRequest(fileUrl: URL, parameter: [String: Any], url: URL, completion:((_ data: Any?, _ error: Error?) -> Void)?) {
        var jsonDictionary: [String: Any] = [:]
        for (k, v) in parameter { jsonDictionary.updateValue(v, forKey: k ) }

        Alamofire.upload(multipartFormData:
            {
                (multipartFormData) in
                
                let filename  = fileUrl.lastPathComponent
                
                let fileData = try? Data(contentsOf: fileUrl)
                let mimetype  = self.mimeType(fileUrl: fileUrl)
                
                multipartFormData.append(fileData!, withName: "img", fileName: filename ,mimeType:"application/octet-stream")
                for (key, value) in jsonDictionary
                {
                    if let data = (value as AnyObject).data(using: String.Encoding.utf8.rawValue) {
                        multipartFormData.append(data, withName: key)
                    }
                }
        }, to:url,headers:nil)
        { (result) in
            switch result {
            case .success(let upload,_,_ ):
                upload.uploadProgress(closure: { (progress) in
                    //Print progress
                })
                upload.responseJSON
                    { response in
                        DispatchQueue.main.async {
                            if let error = response.error {
                                print("Response Error=\(String(describing: error.localizedDescription))")
                                completion?(nil, error)
                            }
                            else {
                                if let json = response.request?.value {
                                    print("JSON: \(json)") // serialized json response
                                }
                                
                                if let dataTemp = response.data, let strDataTemp = String(data:dataTemp, encoding: .utf8){
                                    print("Response Data -> \(strDataTemp)")
                                    guard let dataDict = strDataTemp.jsonParseDictionary() else{
                                        completion?(nil, nil) //Error(domain: ERROR_HTTPAPI, code: 0, userInfo: ["Issue": "Data Not Found"])
                                        return
                                    }
                                    if !dataDict.isEmpty {
                                        completion?(dataDict, nil)
                                        return
                                    }
                                    completion?(nil, nil) //Error(domain: ERROR_HTTPAPI, code: 0, userInfo: ["Issue": "Data Not Found"])
                                }
                                else{
                                    completion?(nil, nil)
                                }
                            }
                        }}
            case .failure(_):
                completion?(nil, nil)
                break
            }
        }
    }

以上是关于text Alamofire - 使用Swift 3上传文件的主要内容,如果未能解决你的问题,请参考以下文章

如何通过 Alamofire 在 Swift 3 中向 MySQL 插入数据?

AlamoFire:如何获取 responseJSON 值

使用 Swift 3 和 Alamofire 4 后没有得到响应

在 Swift 中将 Alamofire 结果解析为对象(使用:Alamofire、SwiftyJSON 和 ObjectMapper)

使用 Alamofire 搜索从 swift 2 转换为 swift 3 时出错

Swift - 使用 alamofire 发布请求