簡體   English   中英

Swift Vapor 4 上傳、驗證、調整圖像文件大小

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

我正在嘗試將照片發布到蒸汽 4 服務器。 我將團隊名稱作為字符串發送,將圖像作為數據發送。

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

我想在驗證其大小不超過 1MB 后上傳照片,並且 mimetype 是圖像類型(jpg,jpeg,png),然后將該圖像調整為 300px*300px,最后將其保存到public\uploads目錄.

我不知道該怎么做。

這是我的代碼。

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
}

代碼也應該適用於 ubuntu 服務器 VPS 雲實例。

經過兩天的測試,我能夠使用SwiftGD做到這一點,所以我想出了這個..希望它有用。

圖像驗證

// 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 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