2017-10-22 3 views
-1

나는 iOS에서 alamofire를 사용하여 엑셀 파일을 업로드하려고합니다. 내 파일 경로가업로드는 alamofire를 사용하여 엑셀

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

하고 코드가 나는

// 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) 
    } 

내가 fileURL이 전무

가 어떻게 번들로 내 파일 경로 alamofire을 통과 할 수 얻을 사용할 수 있습니까?

Alamofire 버전 : 4 엑스 코드 버전 : 8.2.1 스위프트 버전 : 3 플랫폼 (들) Alamofire을 실행 : 아이폰 OS 맥 OS 버전 실행 엑스 코드 : 10

+0

디렉토리에 대해 잊어 버려. 하위 디렉토리를 지정하지 않고 리소스 파일에 Bundle.url 메소드를 사용하기 만하면됩니다. Bundle.url이 사용자의 위치가 아니라 위치를 찾는 책임입니다. // 또한 파일이 프로젝트에서 실제로 복사 (참조되지 않음)되었는지 확인하고 앱과 동일한 대상을 갖고 있는지 확인하십시오. – Moritz

+0

fileURL = Bundle.main.url (forResource : "appImportContacts", withExtension : "xls")을 사용했지만 fileURl이 032입니다. –

+0

이는 파일이 실제로 Bundle에 없거나 올바른 권한이 없다는 것을 의미합니다. 목표. – Moritz

답변

0

나는 해결책을 발견

// 
// 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)) 
    } 
} 
} 
관련 문제