简体   繁体   English

Swift Vapor 4 上传、验证、调整图像文件大小

[英]Swift Vapor 4 upload , validate , resize an image file

I am trying to post a photo to the vapor 4 server.我正在尝试将照片发布到蒸汽 4 服务器。 I am sending a Team name as a string and an image as data.我将团队名称作为字符串发送,将图像作为数据发送。

struct SendTeam: Content {
    var name: String
    var img: Data
}

I want to upload the photo after validating its size to be not more than 1MB, and mimetype is of type image like (jpg, jpeg, png), then resize that image to 300px*300px and finally save it to the public\uploads directory.我想在验证其大小不超过 1MB 后上传照片,并且 mimetype 是图像类型(jpg,jpeg,png),然后将该图像调整为 300px*300px,最后将其保存到public\uploads目录.

I am not able to figure out how to do that.我不知道该怎么做。

Here is my code.这是我的代码。

func create(req: Request) async throws -> SendTeam {
    let team = try req.content.decode(SendTeam.self)
    
    let path = req.application.directory.publicDirectory + "originals/" + team.name + "-\(UUID())"
    
    try await req.fileio.writeFile(.init(data: team.img), at: path)
    
    if team.name.count < 4 || team.name.count > 20 {
        throw Abort(.badRequest, reason: "wrong name")
    }
    
    return team
}

Code should work on ubuntu server VPS cloud instance as well.代码也应该适用于 ubuntu 服务器 VPS 云实例。

After Two Days of Testing, I am able to do that using SwiftGD , So I came up with this.. hope it is useful.经过两天的测试,我能够使用SwiftGD做到这一点,所以我想出了这个..希望它有用。

Image Validation图像验证

// Do not forget to decode the image to File type Not Data type
let img = team.img

if img.data.readableBytes > 1000000  {
    errors.append( "error ... image size should not exceed 1 mb")
}

if !["png", "jpeg", "jpg"].contains(img.extension?.lowercased()) {
    errors.append("extension is not acceptable")
}

    let imageNewNameAndExtension = "\(UUID())"+".\(img.extension!.lowercased())"

The upload an resize part上传调整大小部分

// The upload Path
        let path = req.application.directory.publicDirectory + "uploads/" + imageNewNameAndExtension
// The path to save the resized img
        let newPath = req.application.directory.publicDirectory + "uploads/teams/" + imageNewNameAndExtension
        
        // SwiftNIO File handle
        let handle = try await req.application.fileio.openFile(path: path,mode: .write,flags:.allowFileCreation(posixMode:0x744),eventLoop: req.eventLoop).get()
        
        // Save the file to the server
    req.application.fileio.write(fileHandle:handle,buffer:img.data,eventLoop: req.eventLoop).whenSuccess { _ in
// SwiftGD part to resize the image
            let url = URL(fileURLWithPath: path)
            let newUrl = URL(fileURLWithPath: newPath)
            let image = Image(url: url)
            if let im = image {
                if let mg = im.resizedTo(width: 250, height: 250){
                    mg.write(to: newUrl)
                }
            }
            
            try? handle.close()
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM