Dmitriy Greh
Dmitriy Greh

Reputation: 684

How to use vapor for uploading/downloading image?

Now: i am uploading data and saving it to my public folder:

let info = req.data
            guard let fileBytes = info["photo"]?.bytes
            else {
                var answerJson = JSON();
                try answerJson.set("success", "false");
                return answerJson
            }

            let dir = URL(fileURLWithPath: self.config.workDir).appendingPathComponent("Public/FleaMarketProductImages")
            let dirWithImage = dir.appendingPathComponent("test3.jpg")
            let fileManager = FileManager()
            let data = Data(bytes: fileBytes)
            fileManager.createFile(atPath: dirWithImage.path, contents: data, attributes: nil)

Then on device for downloaing this file i am doing next:

 Alamofire.download(url).responseData { response in
            if let data = response.result.value {
                completionHandler(data)
            }
        }

I am getting some data, but when i do UIImage(data: data), i dont see my image. Where i did something wrong? Maybe there is another way to do it. And files in my public directory dont looks like image. They just files. Maybe do you know how to save it like an image????

Upvotes: 1

Views: 1094

Answers (1)

Nick
Nick

Reputation: 5180

The uploaded image will be one part of a multi-part request, so you need to use just the part that contains the image. .bytes will give you the whole request. I use:

guard let fileBytes = info.formData?["photo"]?.part.body

Or

guard let fileBytes = info?["photo"]?.part.body

if you aren't using a form.

Upvotes: 2

Related Questions