Search code examples
iosswiftexcelalamofire

upload excel using alamofire


i try to upload an excel file using alamofire in iOS. my file path is

file:///Users/macbook/Library/Developer/CoreSimulator/Devices/75477755-3367-41DE-B3D2-A2E22C7AE069/data/Containers/Data/Application/45CB65D0-0B7C-4F17-89AA-2163301F2E6B/Documents/appImportContacts.xls

and the code I use

    // import Alamofire
func uploadWithAlamofire(filePath : String ) {

    let url = URL(fileURLWithPath: filePath)//"/foo/bar/file.text")
    let dirUrl = url.deletingLastPathComponent()
    print(dirUrl.path)
    // Output: /foo/bar

    let fileURL = Bundle.main.url(forResource: "appImportContacts", withExtension: "xls", subdirectory: dirUrl.path)

    Alamofire.upload(fileURL!, to: "http://192.168.1.213/api/app/UploadExcelFile").responseJSON { response in
        debugPrint(response)
    }

I get fileURL nil

How can I make my file path as Bundle to pass to alamofire?

Alamofire version:4 Xcode version:8.2.1 Swift version:3 Platform(s) running Alamofire:iOS macOS version running Xcode:10


Solution

  • I found the solution

    //
    //  HowToDownloadViewController.swift
    //  WhiteSms
    //
    //  Created by MacBook on 7/26/1396 AP.
    //  Copyright © 1396 AP IPE. All rights reserved.
    //
    
    import UIKit
    import FileExplorer
    import Alamofire
    import HandyJSON
    import SwiftyJSON
    
    class ImportExcelViewController: UIViewController, FileExplorerViewControllerDelegate {
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        // Do any additional setup after loading the view.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    
    
    
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    @IBAction func onDownload_Click(_ sender: Any) {
    
    
        // Create destination URL
        let documentsUrl:URL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
        let destinationFileUrl = documentsUrl.appendingPathComponent("appImportContacts.xls")
    
        //Create URL to the source file you want to download
        let fileURL = URL(string: "http://192.168.1.213/downloads/appImportContacts.xls")
    
        let sessionConfig = URLSessionConfiguration.default
        let session = URLSession(configuration: sessionConfig)
    
        let request = URLRequest(url:fileURL!)
    
        let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
            if let tempLocalUrl = tempLocalUrl, error == nil {
                // Success
                if let statusCode = (response as? HTTPURLResponse)?.statusCode {
                    print("Successfully downloaded. Status code: \(statusCode)")
                }
    
                do {
                    try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
                } catch (let writeError) {
                    print("Error creating a file \(destinationFileUrl) : \(writeError)")
                }
    
            } else {
                print("Error took place while downloading a file. Error description: %@", error?.localizedDescription);
            }
        }
        task.resume()
    
    
    
    }
    
    @IBAction func onUpload_Click(_ sender: Any) {
        let fileExplorer = FileExplorerViewController()
        fileExplorer.canRemoveFiles = true //specify whether user is allowed to remove files
        fileExplorer.canRemoveDirectories = false //specify whether user is allowed to remove directories
    
    
        fileExplorer.delegate = self
        self.present(fileExplorer, animated: true, completion: nil)
    
    
    }
    
    public func fileExplorerViewControllerDidFinish(_ controller: FileExplorerViewController) {
    
    }
    
    public func fileExplorerViewController(_ controller: FileExplorerViewController, didChooseURLs urls: [URL]) {
        //Your code here
        print(urls)
    
        var fileAddress = urls[0]
    
        uploadWithAlamofire(filePath: urls[0].absoluteString)
    
    }
    
    // import Alamofire
    func uploadWithAlamofire(filePath : String ) {
    
        let url = URL(fileURLWithPath: filePath)//"/foo/bar/file.text")
        let dirUrl = url.deletingLastPathComponent()
        print(dirUrl.path+"/appImportContacts.xls")
        // Output: /foo/bar
    
    
    
        let filePath = dirUrl.path+"/appImportContacts.xls"
    
        var bytes = [UInt8]()
    
        if let data = NSData(contentsOfFile: filePath) {
    
            var buffer = [UInt8](repeating: 0, count: data.length)
            data.getBytes(&buffer, length: data.length)
            bytes = buffer
        }
    
    
        Alamofire.upload(multipartFormData: {
            multipartFormData in
            multipartFormData.append(Data(fromArray: bytes), withName: "appImportContacts",fileName: "appImportContacts.xls", mimeType: "application/octet-stream")
        },
                         to:"http://192.168.1.213/api/app/UploadExcelFile")
        {
            (result) in
            switch result {
            case .success(let upload, _, _):
    
                upload.uploadProgress(closure: { (progress) in
                    print("Upload Progress: \(progress.fractionCompleted)")
                })
    
                upload.responseJSON { response in
                    print(response.result.value)
                }
    
            case .failure(let encodingError):
                print(encodingError)
            }
        }
    }
    }
    extension Data {
    
    init<T>(fromArray values: [T]) {
        var values = values
        self.init(buffer: UnsafeBufferPointer(start: &values, count: values.count))
    }
    
    func toArray<T>(type: T.Type) -> [T] {
        return self.withUnsafeBytes {
            [T](UnsafeBufferPointer(start: $0, count: self.count/MemoryLayout<T>.stride))
        }
    }
    }