32

我正在使用 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)")
        }

    }

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

4

6 回答 6

43

首先,在文件系统中,您可以获得带有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)")
}
于 2017-05-05T07:19:41.203 回答
24

斯威夫特 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
}
于 2017-11-08T18:15:39.540 回答
13

斯威夫特 4.1 & 5

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
    }
于 2018-06-20T15:39:44.133 回答
12

使用最新版本的 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)
}
于 2017-07-24T09:58:14.707 回答
6
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
    }
}
于 2020-06-03T04:48:34.823 回答
0

工作解决方案:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    
    if let videoURL = info[UIImagePickerController.InfoKey.mediaURL] as? NSURL{
        print(videoURL)
        
        do {
            let resources = try videoURL.resourceValues(forKeys:[.fileSizeKey])
            let fileSize : Int = resources.values.first as! Int
            print ((fileSize/1024/1024) )
        } catch {
            print("Error: \(error)")
        }
    }
    
}
于 2022-02-03T11:40:35.060 回答