Vapor Swift中如何删除FileIO收集存储的文件?
Vapor 实现文件删除功能的方案
Vapor 4 的 FileIO 确实没有直接封装删除文件的接口,你可以通过以下两种常用方式实现:
方案1:使用 Foundation 的 FileManager(简单同步实现)
适合对性能要求不高、删除文件体积小的场景,代码如下:
import Foundation func deleteFile(at path: String) throws { let fileManager = FileManager.default if fileManager.fileExists(atPath: path) { try fileManager.removeItem(atPath: path) } } // 在路由中调用示例 app.delete("files") { req async throws -> HTTPStatus in let filePath = req.application.directory.workingDirectory + "要删除的文件名" try deleteFile(at: filePath) return .ok }
注意:该方法是同步操作,删除大文件时可能会阻塞当前事件循环,高并发场景更推荐下面的非阻塞实现
方案2:使用 SwiftNIO 非阻塞删除(推荐高并发场景)
Vapor 底层依赖 SwiftNIO,你可以直接调用 NonBlockingFileIO 的删除方法,完全适配 Vapor 的异步编程模型,不会阻塞事件循环:
app.delete("files") { req async throws -> HTTPStatus in let filePath = req.application.directory.workingDirectory + "要删除的文件名" let fileIO = req.application.fileio // 异步执行删除操作 try await fileIO.remove(path: filePath, eventLoop: req.eventLoop).get() return .ok }
内容的提问来源于stack exchange,提问作者Wendell
相关产品推荐
相关产品推荐

