Image Upload in Vapor 3 using PostgreSQL

后端 未结 3 1710
没有蜡笔的小新
没有蜡笔的小新 2021-01-04 11:16

I\'m following this guys Martin Lasek Tutorials and now i\'m at \"image upload\". It seems that no one has the answer to the question \"How do you upload images i Vapor 3\"

3条回答
  •  半阙折子戏
    2021-01-04 11:31

    This uses automatic decoding of the multi-part form:

    router.get("upload") {
        request -> Future in
        return try request.view().render("upload")
    }
    
    struct ExampleUpload: Content {
        let document: File
    }
    
    // this saves the file into a Question
    router.post(ExampleUpload.self, at:"upload") {
        request, upload -> Future in
        let question = try Question()
        question.imageData = upload.document.data
        question.imageName = upload.document.filename
        return question.save(on:request).transform(to: HTTPResponseStatus.ok)
    }
    

    The upload.leaf file is:

    Using the type File enables the local filename of the uploaded file to be accessed as well as the file data. If you add in the rest of the Question fields to the ExampleUpload structure, you can use the route to capture the whole form's fields.

提交回复
热议问题