如何使用 async/await 实现上传和下载文件的API
fade 2022-04-05 13:04:40
上传到 public 目录
下载也是从 public 目录获取
app.post("upload") { req in
"Upload file..."
}
app.get(":filename") {req in
"fetch file ..."
}
1个回答
1
我写了一个例子,upload是post的multipart/form-data格式,upload-stream是post的binary格式。
其中multipart/form-data的文件会先加载到内存里面所以需要设置最大大小,stream的方式是用不会占用大量系统内存的所以不限传输的文件大小限制。
import Vapor
class FileController: RouteCollection {
func boot(routes: RoutesBuilder) throws {
let fileRouter = routes.grouped("file")
fileRouter.on(.POST, "upload", body: .collect(maxSize: "10mb"),use: upload)
fileRouter.on(.POST, "upload-stream", body: .stream, use: uploadStream)
}
struct FileParam: Content {
let file: File
}
func upload(req: Request) async throws -> HTTPStatus {
let param = try req.content.decode(FileParam.self)
let path = req.application.directory.publicDirectory + param.file.filename
let fileHander = try await req.application.fileio.openFile(path: path,
mode: .write,
flags: .allowFileCreation(posixMode: 0x744),
eventLoop: req.eventLoop).get()
try await req.application.fileio.write(fileHandle: fileHander, buffer: param.file.data, eventLoop: req.eventLoop).get()
try fileHander.close()
return .ok
}
func uploadStream(req: Request) async throws -> HTTPStatus {
let filename: String = try req.query.get(at: "filename")
let path = req.application.directory.publicDirectory + filename
let fileHander = try await req.application.fileio.openFile(path: path,
mode: .write,
flags: .allowFileCreation(posixMode: 0x744),
eventLoop: req.eventLoop).get()
@Sendable func deal(bodyResult: BodyStreamResult) async throws {
switch bodyResult {
case .buffer(let data):
try await req.application.fileio.write(fileHandle: fileHander, buffer: data, eventLoop: req.eventLoop).get()
case .end:
try fileHander.close()
case .error(let err):
throw err
}
}
req.body.drain { (bodyResult:BodyStreamResult) -> EventLoopFuture<Void> in
let promise = req.eventLoop.makePromise(of: Void.self)
promise.completeWithTask {
try await deal(bodyResult: bodyResult)
}
return promise.futureResult
}
return .ok
}
}
2022-04-12 16:48:59
更多