ios - 有没有办法通过 Alamofire 上传 doc、pdf 文件?

标签 ios file-upload alamofire swift4 xcode9

我浏览了很多帖子但不满意,目前我正在使用File Explorer Framework并且工作正常,但是当我选择一个文件(文件可以是 pdf、docs 或任何文本文件)时,我将如何将该文件上传到服务器中?

let fileExplorer = FileExplorerViewController()
fileExplorer.canChooseFiles = true //specify whether user is allowed to choose files
fileExplorer.canChooseDirectories = false //specify whether user is allowed to choose directories
fileExplorer.allowsMultipleSelection = true //specify whether user is allowed to choose multiple files and/or directories
fileExplorer.delegate = self

self.present(fileExplorer, animated: true, completion: nil)

及其委托(delegate)方法
public func fileExplorerViewController(_ controller: FileExplorerViewController, didChooseURLs urls: [URL]) {
    //Your code here
}

现在如何通过从委托(delegate)方法获取文件 url 来上传文件?

任何帮助将不胜感激。

谢谢

最佳答案

你可以使用文档选择器

fileprivate func p_documentclicked() { 
    let importMenu = UIDocumentMenuViewController(documentTypes: ["public.text", "public.data","public.pdf", "public.doc"], in: .import) 
    importMenu.delegate = self 
    self.present(importMenu, animated: true, completion: nil) 
}

然后它有一个委托(delegate)方法
internal func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) { 
   let cico = url as URL 
   print(cico) 
   self.downloadfile(URL: cico as NSURL) 
}

拥有 URL 后您可以下载文件,然后上传文件。
fileprivate func downloadfile(URL: NSURL) {
        let sessionConfig = URLSessionConfiguration.default
        let session = URLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
        var request = URLRequest(url: URL as URL)
        request.httpMethod = "GET"
        let task = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
            if (error == nil) {
                // Success
                let statusCode = response?.mimeType
                print("Success: \(String(describing: statusCode))")
                DispatchQueue.main.async(execute: {
                    self.p_uploadDocument(data!, filename: URL.lastPathComponent!)
                })

                // This is your file-variable:
                // data
            }
            else {
                // Failure
                print("Failure: %@", error!.localizedDescription)
            }
        })
        task.resume()
    }

您可以使用此方法上传 doc 和 pdf 文件:
fileprivate func p_uploadDocument(_ file: Data,filename : String) {

        let parameters = ["yourParam" : "sample text"]
        let fileData = file
        let URL2 = try! URLRequest(url: "your api", method: .post, headers: ["Authorization" :"your auth key"])

        Alamofire.upload(multipartFormData: { (multipartFormData) in

            multipartFormData.append(fileData as Data, withName: "upfile", fileName: filename, mimeType: "text/plain")


            for (key, value) in parameters {
                multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
            }
        }, with: URL2 , encodingCompletion: { (result) in

            switch result {
                case .success(let upload, _, _):
                    print("s")
                    upload.responseJSON {
                        response in
                        if let JSON = response.result.value as? [String : Any]{
                            let messageString = JSON["message"] as? String
                             // use the JSON
                            }else {
                               //error hanlding
                            }

                        }
                    }
                case .failure(let encodingError):
                   // error handling
                }
            }
        )
    }

关于ios - 有没有办法通过 Alamofire 上传 doc、pdf 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47453832/

相关文章:

javascript - 文件上传完成后如何将 uploadcare 小部件重置为原始状态

javascript - 替换和预览多张图片上传

Swift 3 和 Alamofire 4.0,需要时请求

swift - Alamofire NetworkActivityIndi​​catorManager.sharedManager.isEnabled = true ,使用未解析的标识符

ios - Firebase pod 安装错误

ios - 字符串?不能转换为 'StringLiteralConvertible' & ?!在 swift

AngularJs 服务、文件上传、Laravel

swift - AlamoFire POST 可以工作,但返回 NSURLErrorDomain 错误

ios - ABGroupCreate 不适用于 Exchange

ios - 获取 Google Maps 步行路线 JSON 而不是驾驶