Swift-从网址获取文件大小 [英] Swift - Get file size from url

查看:104
本文介绍了Swift-从网址获取文件大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i am using documentPicker to get url path of any document and then uploaded to the database. I am choosing file (pdf, txt ..) , the upload is working but i want to limit the size of the file .

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

    }

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

I get the error message , this file does not exist , where does the document picker save the file and how to get his attributes.

推荐答案

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

First of all, in the file system you get the path of a URL with the path property.

self.path = url.path

但是您根本不需要.您可以直接从URL检索文件大小:

But you don't need that at all. You can retrieve the file size from the URL directly:

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

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

这篇关于Swift-从网址获取文件大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆