环境:
Vapor (v4.77+)
MacOS v13.4.1
服务器位于我的 Mac 本地:http://localhost:8080/upload
这与我的 Xcode iOS 模拟器同时运行。
结果:
初始有效负载:PayloadModel(文件名:“ToiletOnTheSea”,内容类型:“image/png”,数据:466220 字节)状态代码:413
这是数据模型:
struct PayloadModel: Codable {
let filename: String
let contentType: String
let data: Data
enum CodingKeys: String, CodingKey {
case filename
case contentType
case data
}
}
这是 iOS 客户端:
func uploadImageToServer() async {
let sampleImage = "ToiletOnTheSea"
guard let image = UIImage(named: sampleImage), let imageData = image.pngData() else {
showAlert("No Image", "I couldn't access \(sampleImage)")
print("Error converting image to data")
return
}
let payload = PayloadModel(filename: sampleImage, contentType: "image/png", data: imageData)
var request = URLRequest(url: serverURL)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
print("Initial Payload: ", payload)
do {
let jsonData = try JSONEncoder().encode(payload)
request.httpBody = jsonData
let (data, response) = try await URLSession.shared.data(for: request)
if let httpResponse = response as? HTTPURLResponse {
print("Status Code: \(httpResponse.statusCode)")
if let serverData = try? JSONDecoder().decode(ServerResponse.self, from: data) {
let contentType = serverData.payload.contentType
let message = serverData.message
let filename = payload.filename
let count = payload.data.count
print("contentType: ", contentType)
print("filename: ", filename)
print("data count: ", count)
showAlert("Server Data", message)
} else {
showAlert("Server-Response Error", "Unable to decode server response")
}
// Process data if needed
} else {
print("Error: Unexpected response")
}
} catch {
showAlert("Error", "\(error)")
}
}
这是 Vapor v4 对应的服务器(在路由文件中):
struct ServerResponse: Content {
let message: String
let payload: PayloadModel?
// Provide an initializer that takes the required parameters
init(message: String, payload: PayloadModel? = nil) {
self.message = message
self.payload = payload
}
// Implement the required initializer for the Decodable protocol
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
message = try container.decode(String.self, forKey: .message)
payload = try container.decodeIfPresent(PayloadModel.self, forKey: .payload)
}
// Define coding keys to match the properties
enum CodingKeys: String, CodingKey {
case message
case payload
}
}
func storeImage(req: Request) async throws -> ServerResponse {
// let payload = try req.content.decode(PayloadModel.self)
let response = ServerResponse(message: "Holy Shit, Batman! I'm from storeImage!!", payload: nil)
return response
}
我将代码减少到最少,以找出尺寸拒绝的原因。
我已经发送(发布)了一个成功且没有大小错误的字符串。
- 我原以为存在蒸汽尺寸限制,所以我将其设置为比图像尺寸更高的尺寸,这并没有改变结果。因此我评论道:
问题:为什么会出现尺寸问题,是什么原因造成的以及补救措施:
[警告] Abort.413:有效负载太大 [请求 ID:3224652A-0F82-43E9-AA7A-92496FB7781D]