首页 > 解决方案 > 如何将图像、pdf、音频、视频和任何文件系统从 iphone 本地内存上传到服务器(API)

问题描述

我必须将任何类型的文件系统从本地手机内存上传到给定的 API。有没有简单的方法请帮忙。

标签: iosobjective-cswiftiphonexcode

解决方案


您可以使用 Alamofire 库。 https://github.com/Alamofire/Alamofire

Alamofire.upload(multipartFormData: { (multipartFormData) in
    if let parameters = parameters {
        for (key, value) in parameters {
            if let value = value as? String {
                multipartFormData.append(value.data(using: .utf8)!, withName: key)
            }else if let _image = value as? UIImage, let image = _image.resized(toWidth: 500) {
                if let jpegData = image.jpegData(compressionQuality: 0.5) {
                    multipartFormData.append(jpegData, withName: key, fileName: "post.jpeg", mimeType: "image/jpeg")
                }else if let pngData = image.pngData() {
                    multipartFormData.append(pngData, withName: key, fileName: "post.png", mimeType: "image/jpeg")
                }
            }else {
                multipartFormData.append(Data(from: value), withName: key)
            }
        }
    }
}, usingThreshold: UInt64.init(), to: urlString, method: method, headers: headers, encodingCompletion: { (result) in
    switch result {
    case .success(let upload, _, _):
        upload.responseJSON { response in
            if let responseData = response.result.value as? NSDictionary {
                completion(responseData, response.data, response.result)
            }else if let responseData = response.result.value as? [String: Any] {
                completion(responseData as NSDictionary, response.data, response.result)
            }else {
                completion([:], nil, response.result)
            }
        }
        break
    case .failure(let encodingError):
        completion([:], nil, .failure(encodingError))
        break
    }
})

推荐阅读