簡體   English   中英

如何將文件保存在 SwiftUI 2 中的變量中

[英]How to save a file in a variable in SwiftUI 2

我使用文件導入器獲得了文件的 URL。 現在我想將文件存儲在一個變量中,以便我可以將它發送到服務器。

.fileImporter(isPresented: $openfile, allowedContentTypes: [.audio,.pdf,.png, .text, .jpeg], allowsMultipleSelection: false) { (res) in
            
            do{
                let fileURL = try res.get()
                //getting file name
                self.fileName = fileURL.last?.lastPathComponent ?? "File Uplaoded"
                print(fileURL)
            }catch{
                print("Error reading docs")
                print(error.localizedDescription)
            }
        }

如何將文件保存在 fileURL 的變量中?

stackoverflow 答案向您展示了如何從 go 獲取文件內容。 您必須根據您的代碼調整答案,例如:

 var fileData: Data?
 
 .fileImporter(isPresented: $openfile, allowedContentTypes: [.audio,.pdf,.png, .text, .jpeg], allowsMultipleSelection: false) { (res) in           
        do{
            let fileURL = try res.get()
            if let url = fileURL.first {
                fileName = url.lastPathComponent
                fileData = try Data(contentsOf: url)
                print("\n fileName: \(fileName) \n url: \(url) \n fileData: \(fileData)")
            }
        }catch{
            print("Error reading docs")
            print(error.localizedDescription)
        }
    }
 

然后您可以使用 fileData 發送到服務器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM