美文网首页
Alamofire 5.0.0-beta.5 带参数上传多文件调

Alamofire 5.0.0-beta.5 带参数上传多文件调

作者: 盟主直播Libx | 来源:发表于2019-10-08 14:53 被阅读0次

Alamofire找了好些资料,最新版本5.0.0-beta. 5的网络上太少,这里记录一下,方便刚学习的同学学习使用。

1. 普通的get/post/put/delete等方式的封装函数

    /** get/post/其他请求模式,具体看 HTTPMethod */

    static func request(method: HTTPMethod, param: Parameters, success: @escaping (_success: Any) -> Void, fail: @escaping (_fail: Error) -> Void, from URLString: String) {

        AF.request(URLString, method: method, parameters: param, headers:nil, interceptor:nil) .responseJSON { (dataResponse) in

           switch dataResponse.result {

            case .failure(let error):

                fail(error)

            case .success(let json):

                success(json)

            }

        }

    }

调用示例:

 let ExURLString = "http://192.168.0.1:8088/api/Ex"

        let param = [

            "username" : "bbb",

            "drama_name"   "haha",

            "telephone" : NSNumber.init(value:13011111111),

            "id" : NSNumber.init(value:1),

            ] as [String : Any]

        LFAlamofire.request(method: .post, param: param, success: { (json) in

            print("json = \(json)")

        }, fail: { (error) in

            print("error = \(error)")

        }, from: ExURLString)

2. 多文件上传的方式的封装函数(带参数)

/// 获取文件类型

func getFileType(fileData data : Data) -> String {

    var bytes = [UInt8](data)

    switch bytes[0] {

    case 0xFF:

        return "image/jpeg";

    case 0x89:

        return "image/png";

    case 0x47:

        return "image/gif";

    case 0x49, 0x4D:

        return "image/tiff";

    case 0x52:

        return "application/octet-stream";

    default:

        return "application/octet-stream";

    }

}

 /** 上传多文件 */

public static func upload<T>(files: [T], param: Parameters, progress: @escaping (_ progress: Progress) -> Void, success: @escaping (_ success: Any) -> Void, fail: @escaping (_ fail: Error) -> Void, to URLString: String) {

        AF.upload(multipartFormData: { (formData) in

            // 组装图片数据

            var fileNameCount = 1

            for file in files {

                if file is NSString {

                    if let data = try? Data.init(contentsOf: URL.init(string: file as! String)!) {

                        formData.append(data, withName: String(fileNameCount), fileName: uploadFileOfServerFileKey, mimeType: getFileType(fileData: data))

                    } else {

                        JGPrint("文件路径出错")

                    }

                } else if file is UIImage {

                    let data = (file as! UIImage).jpegData(compressionQuality: 1.0)!

                    formData.append(data, withName: String(fileNameCount), fileName: uploadFileOfServerFileKey, mimeType: getFileType(fileData: data))

                }

                fileNameCount += 1

            }

            // 组装参数数据

            for (key, value) in param {

                if value is NSNumber {

                    let valueString = (value as! NSNumber).stringValue

                    formData.append(valueString.data(using: .utf8)!, withName: key)

                } else if value is String {

                    formData.append((value as! String).data(using: .utf8)!, withName: key)

                }

            }

        }, to: URLString, usingThreshold: (5*1024*1024), method: .post, headers: getHttpHeader(URLString: URLString), interceptor: nil, fileManager: .default) .responseJSON { (dataResponse) in

            updateToken(response: dataResponse)

            switch dataResponse.result {

            case .failure(let error):

                fail(error)

            case .success(let json):

                success(json)

            }

            } .uploadProgress { (uploadProgress) in

                progress(uploadProgress)

        }

    }

调用示例:

      let image1: UIImage = UIImage.init(named: "1.jpg")!

        let image2: UIImage = UIImage.init(named: "juben")!

        let image3: UIImage = UIImage.init(named: "guanyu")!

        LFAlamofire.upload(files: [image1,image2,image3], param: param, progress: { (progress) in

            print("progress = \(progress.completedUnitCount/progress.totalUnitCount)")

        }, success: { (json) in

            print("json = \(json)")

        }, fail: { (error) in

            print("error = \(error.localizedDescription)")

        }, to: loginUrlString)

相关文章

网友评论

      本文标题:Alamofire 5.0.0-beta.5 带参数上传多文件调

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