首页 > 解决方案 > 如何为具有给定前缀的 URL 提供文件?

问题描述

语境

我一直通过 Vapor (v4) 成功地提供文件:

func configure(_ app: Application) throws {
   // ...
   app.middleware.use(FileMiddleware(publicDirectory: app.directory.publicDirectory))
   // ...
}

问题

就像,如果我有,一个人会通过while/Public/foobar.txt请求它,但不会匹配任何东西。GET /files/foobar.txtGET /foobar.txt

考虑的方法

标签: swiftvapor

解决方案


似乎它FileMiddleware只能在全局范围内工作,而不是像中间件实例通常那样附加到路由组。

如果您在项目文件夹中有一个名为 Private 的文件夹(即保存您的 Public 文件夹的同一文件夹),那么访问其中包含的文件很简单:

public func configure(_ app: Application) throws {
    app.get("files", "**") { req -> Response in
        let filepath = req.parameters.getCatchall()
        let workPath = DirectoryConfiguration.detect().workingDirectory
        var fileURL = URL(fileURLWithPath: workPath)
            .appendingPathComponent("Private", isDirectory: true)
            .appendingPathComponent(filepath.joined(separator: "/"), isDirectory: false)
        return req.fileio.streamFile(at: fileURL.path)
    }
}

假设您正在运行这个最小的项目localhost:8080,它将通过 URL 提供文件:

http://localhost:8080/files/path/to/myFile.txt

编辑

OP 仅表示平面文件。根据评论,使其适用于Private/. 如果文件/路径不存在,我会让您添加操作。


推荐阅读