我已经设置了AWS S3存储桶,并且可以使用Vapor 3和Postman(PUT -request并带有标头:[“ x-amz-acl”:“ public-read”])在那里上传文件,但是希望通过浏览器做到这一点(我使用的是叶子)。
那么如何从浏览器上传图像文件?我是HTML,AWS S3和Vapor的新手。
我正在使用:
我按照本教程设置了所有内容(get请求和存储桶策略除外):https://fivedottwelve.com/blog/using-amazon-s3-with-vapor/
获取网址:
func preparePresignedUrl(request: Request) throws -> String {
let baseUrl = awsConfig.url
let imagePath = awsConfig.imagePath
let newFilename = UUID().uuidString + ".png"
guard var url = URL(string: baseUrl) else {
throw Abort(.internalServerError)
}
url.appendPathComponent(imagePath)
url.appendPathComponent(newFilename)
let headers = ["x-amz-acl" : "public-read"]
let s3 = try request.makeS3Signer()
let result = try s3.presignedURL(for: .PUT, url: url, expiration: Expiration.hour, headers: headers)
guard let presignedUrl = result?.absoluteString else {
throw Abort(.internalServerError)
}
return presignedUrl
}
路由处理程序:
func ImagesHandler(_ req: Request) throws -> Future<View> {
let presignedUrl = try preparePresignedUrl(request: req)
let context = PostImageContext(title: "Add Image", url: presignedUrl)
return try req.view().render("addImage", context)
}
一个包含Leaf变量数据的上下文:
struct PostImageContext: Encodable {
let title : String
let url : String
}
Leaf文件(addImage.leaf):
#set("content") {
<h1>#(title)</h1>
<form method="PUT", action="#(url)", enctype="multipart/form-data">
<div class="form-group">
<label>
Choose Image
</label>
<input type="file"
class="form-control-file"/>
</div>
<button type="submit" class="btn btn-primary">
Upload
</button>
</form>
}
#embed("base")
它返回一个错误:
"NoSuchKeyThe specified key does not exist"
我了解到method属性的唯一有效值是get和post,这意味着这是无效的HTML,将被视为,即发送GET请求(解释我得到的错误)。
如何使用Vapor解决此问题?谢谢您的帮助!