简体   繁体   English

将图像从 iOS Alamofire 发送到 Vapor

[英]Send image from iOS Alamofire to Vapor

I have an application where user can update their profile picture.我有一个应用程序,用户可以在其中更新他们的个人资料图片。 The application is developed in SwiftUI and used Alamofire to perform API request and the server is developed with Vapor.该应用程序在 SwiftUI 中开发,并使用 Alamofire 执行 API 请求,服务器使用 Vapor 开发。 When I tried to send the picture to the server, I got this error:当我尝试将图片发送到服务器时,出现此错误:

[ WARNING ] Value required for key 'filename'. [警告]键“文件名”所需的值。 [request-id: A5083FA1-657C-4777-A7FF-9D02E2A66703] [请求 ID:A5083FA1-657C-4​​777-A7FF-9D02E2A66703]

Here is the code from Vapor:这是来自 Vapor 的代码:

private func updatePicture(req: Request) async throws -> Response {
        let file = try req.content.decode(File.self)
        guard let fileExtension = file.extension else { throw Abort(.badRequest)}
        
        return .init(status: .accepted, headers: getDefaultHttpHeader(), body: .empty)
    }

And here is the iOS code:这是 iOS 代码:

func uploadFiles(urlParams: [String], method: HTTPMethod, user: User, image: UIImage, completionHandler: @escaping ((Data?, HTTPURLResponse?, Error?)) -> Void) {
        guard let formattedUrl = URL(string: "\(url)/\(urlParams.joined(separator: "/"))") else {
            completionHandler((nil, nil, nil))
            return
        }
        var headers: HTTPHeaders?
        headers = ["Authorization" : "Bearer \(user.token)"]
        
        let multiPart: MultipartFormData = MultipartFormData()
        multiPart.append(image.jpegData(compressionQuality: 0.9), withName: "data", fileName: "filename", mimeType: "image/jpeg" )

        AF.upload(multipartFormData: multiPart, to: formattedUrl, method: .patch, headers: headers).response { data in
            print(data)
        }.resume()
    }

I followed vapor and Alamofire documentation and I still get this issue.我遵循了蒸汽和 Alamofire 文档,但仍然遇到此问题。

Is anyone can help me with this issues?有人可以帮我解决这个问题吗?

On the Vapor side you have to use struct with File field inside在 Vapor 方面,您必须使用带有 File 字段的 struct

struct PayloadModel: Content {
    let data: File
}

private func updatePicture(req: Request) async throws -> HTTPStatus {
    let payload = try req.content.decode(PayloadModel.self)
    guard let fileExtension = payload.data.extension else {
        throw Abort(.badRequest)
    }

    return .accepted
}

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

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