Swift - 从url获取文件大小

时间:2017-05-05 05:39:52

标签: ios swift filesize uidocumentpickervc

我正在使用documentPicker获取任何文档的url路径,然后上传到数据库。我选择文件(pdf,txt ..),上传工作但我想限制文件的大小。

 public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {

        self.file = url //url
        self.path = String(describing: self.file!) // url to string
        self.upload = true //set upload to true
        self.attachBtn.setImage(UIImage(named: "attachFilled"), for: .normal)//set image
        self.attachBtn.tintColor = UIColor.black //set color tint
        sendbtn.tintColor = UIColor.white //


        do
        {
            let fileDictionary = try FileManager.default.attributesOfItem(atPath: self.path!)
            let fileSize = fileDictionary[FileAttributeKey.size]
            print ("\(fileSize)")
        } 
        catch{
            print("Error: \(error)")
        }

    }

我收到错误消息,此文件不存在,文档选择器在哪里保存文件以及如何获取其属性。

5 个答案:

答案 0 :(得分:23)

首先,在文件系统中,您将获得具有path属性的URL的路径。

self.path = url.path

但你完全不需要它。您可以直接从URL检索文件大小:

<击> self.path = String(describing: self.file!) // url to string

do {
    let resources = try url.resourceValues(forKeys:[.fileSizeKey])
    let fileSize = resources.fileSize!
    print ("\(fileSize)")
} catch {
    print("Error: \(error)")
}

答案 1 :(得分:15)

斯威夫特4:

func sizePerMB(url: URL?) -> Double {
    guard let filePath = url?.path else {
        return 0.0
    }
    do {
        let attribute = try FileManager.default.attributesOfItem(atPath: filePath)
        if let size = attribute[FileAttributeKey.size] as? NSNumber {
            return size.doubleValue / 1000000.0
        }
    } catch {
        print("Error: \(error)")
    }
    return 0.0
}

答案 2 :(得分:8)

Swift 4.1

func fileSize(forURL url: Any) -> Double {
        var fileURL: URL?
        var fileSize: Double = 0.0
        if (url is URL) || (url is String)
        {
            if (url is URL) {
                fileURL = url as? URL
            }
            else {
                fileURL = URL(fileURLWithPath: url as! String)
            }
            var fileSizeValue = 0.0
            try? fileSizeValue = (fileURL?.resourceValues(forKeys: [URLResourceKey.fileSizeKey]).allValues.first?.value as! Double?)!
            if fileSizeValue > 0.0 {
                fileSize = (Double(fileSizeValue) / (1024 * 1024))
            }
        }
        return fileSize
    }

答案 3 :(得分:3)

使用字节计数器格式化程序,使用最新版本的swift来计算文件大小非常容易:

var fileSizeValue:UInt64 = 0

    do {

        let fileAttribute: [FileAttributeKey : Any] = try FileManager.default.attributesOfItem(atPath: url.path)

        if let fileNumberSize: NSNumber = fileAttribute[FileAttributeKey.size] as? NSNumber {
            fileSizeValue = UInt64(fileNumberSize)

            let byteCountFormatter: ByteCountFormatter = ByteCountFormatter()
            byteCountFormatter.countStyle = ByteCountFormatter.CountStyle.file

            byteCountFormatter.allowedUnits = ByteCountFormatter.Units.useBytes
            print(byteCountFormatter.string(fromByteCount: Int64(fileSizeValue)))

            byteCountFormatter.allowedUnits = ByteCountFormatter.Units.useKB
            print(byteCountFormatter.string(fromByteCount: Int64(fileSizeValue)))

            byteCountFormatter.allowedUnits = ByteCountFormatter.Units.useMB
            print(byteCountFormatter.string(fromByteCount: Int64(fileSizeValue)))

        }

    } catch {
        print(error.localizedDescription)
    }

答案 4 :(得分:1)

extension URL {
    func fileSize() -> Double {
        var fileSize: Double = 0.0
        var fileSizeValue = 0.0
        try? fileSizeValue = (self.resourceValues(forKeys: [URLResourceKey.fileSizeKey]).allValues.first?.value as! Double?)!
        if fileSizeValue > 0.0 {
            fileSize = (Double(fileSizeValue) / (1024 * 1024))
        }
        return fileSize
    }
}