Vapor将文件上传到DerivedData而不是项目结构中的Public文件夹



当我尝试通过我的Vapor服务器上传文件时,它总是将文件上传到DerivedData文件夹而不是项目结构中的Public文件夹。

我可以验证文件是在路径中创建的,但路径是在DerivedData目录中的某个地方。为什么?当它不在项目的Public文件夹中时,我将如何服务器这样的文件?

我的上传代码:

func create(request: Request) async throws -> HTTPStatus {
try CreateDogRequest.validate(content: request)
let createDogRequest = try request.content.decode(CreateDogRequest.self)
guard let userId = try request.auth.require(User.self).id else {
throw Abort(.notFound)
}
let dogId = UUID()
let directory = DirectoryConfiguration.detect()
let publicFolder = "Public"
let folderPath = URL(fileURLWithPath: directory.workingDirectory)
.appendingPathComponent(publicFolder, isDirectory: true)
.appendingPathComponent("dogProfiles", isDirectory: true)
.appendingPathComponent(userId.uuidString, isDirectory: true)
.appendingPathComponent(dogId.uuidString, isDirectory: true)
print("Starting writing to path: (folderPath)")
let filePath = folderPath.appendingPathComponent("hello" + ".jpg", isDirectory: false)
try FileManager.default.createDirectory(at: folderPath, withIntermediateDirectories: true)
let data = Data(buffer: createDogRequest.dogImage.data)
try data.write(to: filePath, options: .atomic)
print("file uploaded at: (filePath.relativePath)")
return .ok
}

现在显示文件被上传到了这里:

/Users/<USERNAME>/Library/Developer/Xcode/DerivedData/<PROJECT_HANDLE>/Build/Products/Debug/Public/dogProfiles/62C340CE-262B-4DE4-9E2A-99B3B3126BB6/hello.jpg

为什么?那么我怎样才能送达这样的文件呢?

我调试了DirectoryConfiguration类和detect()方法检查服务器是否通过Xcode运行,它看起来像这样:

#if Xcode
if workingDirectory.contains("DerivedData") {
Logger(label: "codes.vapor.directory-config")
.warning("No custom working directory set for this scheme, using (workingDirectory)")
}
#endif

但有趣的是,如果我把一个文件放入Resource文件夹中读取数据,并使用DirectoryConfigurationdetect()方法并创建该文件的路径,它会发现该文件没有问题?? ?!!为什么?如何?这对我来说是个谜。

这是我为从文件中读取而编写的代码:

let directory = DirectoryConfiguration.detect()
let configDir = "Resources"
let path = URL(fileURLWithPath: directory.workingDirectory)
.appendingPathComponent(configDir, isDirectory: true)
.appendingPathComponent("file.txt", isDirectory: false)
.relativePath

我在这里错过了什么?为什么文件放在Resources文件夹读取,但当我想把一些东西在Public文件夹内,它被放在DerivedData,即使我使用相同的模式时创建path??

你需要在Xcode中设置一个自定义的工作目录,这样Vapor就知道去哪里找了。看到https://docs.vapor.codes/getting-started/xcode/custom-working-directory

再一次,我试着用不同的方式思考,我在谷歌上搜索了一下,发现了这篇文章:

如何得到你的项目文件夹的根目录的路径在完美2.0?

worthbak的答案指向结论,我应该使用swift run从终端运行服务器,并尝试是否创建了文件,猜猜会发生什么?它!

这也解释了我放在Resources文件夹中的文件是如何被读取的,因为它是在一个迁移中,您从猜猜哪里运行?. .终端:)

最新更新