ios Swift -从url获取文件大小

of1yzvn4  于 2023-04-22  发布在  iOS
关注(0)|答案(6)|浏览(159)

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

    }

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

jdzmm42g

jdzmm42g1#

首先,在文件系统中,您将获得具有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)")
}
6yt4nkrj

6yt4nkrj2#

Swift 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
}
nbewdwxp

nbewdwxp3#

Swift 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
    }
xxhby3vn

xxhby3vn4#

使用最新版本的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)
}
8oomwypt

8oomwypt5#

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
    }
}
41ik7eoe

41ik7eoe6#

工作溶液:

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

相关问题