ios - 如何在 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 答案向您展示了如何获取文件内容。您必须根据您的代码调整答案,例如:
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 发送到服务器。
推荐阅读
- javascript - 如何使用 JavaScript 和 Ajax 在服务器上创建/写入/编辑文件?
- c++ - 一次读取 1 和 0 的文件
- python - 将 ssh 连接到域上的用户帐户?
- c++ - 在 C++ 中使用退出函数时如何暂停命令窗口?
- javascript - 附加 DOM 会丢失菜单下拉功能
- android - Firebase 测试实验室结果 - 缺少性能数据
- cytoscape.js - cytoscape 显示沿动画路径的节点之间的流量
- css - 为什么 box-shadow 会像这样出现在元素下方
- c++ - 我将如何返回动态二维向量或字符?
- opengl - 使用矩阵OpenGL绘制线