Swift 5.7
我正试图通过多部分表单数据请求发送3个图像以及其他一些数据到我的服务器。当我尝试用以下代码发送请求时,我的服务器根本没有命中,除非我从请求中删除最后两个图像. 我做错了什么?如果可能的话,我需要能够在同一请求中发送所有3个图像。我把代码缩短到你需要看的部分。我被这事困住了。任何方向都有帮助。
Service.swift
let networker = Networker()
let serverUrl = URL(string: "https://myurl.com")
var urlRequest = URLRequest(url: serverUrl!)
let boundary = UUID().uuidString
urlRequest.httpMethod = "POST"
urlRequest.setValue("multipart/form-data; boundary=(boundary)", forHTTPHeaderField: "Content-Type")
urlRequest.setValue("Bearer (token)", forHTTPHeaderField: "Authorization")
let requestData = networker.buildMultipartImageRequest(boundary: boundary, item: items)
URLSession.shared.uploadTask(with: urlRequest, from: requestData) {(data, response, error) in
...
}.resume()
Networker.swift
func buildMultipartImageRequest(boundary: String, item: ItemForBackend, itemId:UInt = 0) -> Data {
var data = Data()
// add the image data to the raw http request data
data.append("rn--(boundary)rn".data(using: .utf8)!)
data.append("Content-Disposition: form-data; name="images"; filename="(item.filename1)"rn".data(using: .utf8)!)
data.append("Content-Type: image/jpegrnrn".data(using: .utf8)!)
data.append(item.image1)
// If I uncomment these next two portions, the request won't send at all!
// data.append("rn--(boundary)rn".data(using: .utf8)!)
// data.append("Content-Disposition: form-data; name="images"; filename="(item.filename2)"rn".data(using: .utf8)!)
// data.append("Content-Type: image/jpegrnrn".data(using: .utf8)!)
// data.append(item.image2)
//
// data.append("rn--(boundary)rn".data(using: .utf8)!)
// data.append("Content-Disposition: form-data; name="images"; filename="(item.filename3)"rn".data(using: .utf8)!)
// data.append("Content-Type: image/jpegrnrn".data(using: .utf8)!)
// data.append(item.image3)
// add the rest of the item's info to the multipart form data
let paramObj:[String: Any] = item.getParams()
for(key, value) in paramObj {
data.append("rn--(boundary)rn".data(using: .utf8)!)
data.append("Content-Disposition: form-data; name="(key)"rnrn".data(using: .utf8)!)
data.append("(value)rn".data(using: .utf8)!)
}
if itemId != 0 {
data.append("rn--(boundary)rn".data(using: .utf8)!)
data.append("Content-Disposition: form-data; name="itemId"rnrn".data(using: .utf8)!)
data.append("(itemId)rn".data(using: .utf8)!)
}
data.append("rn--(boundary)--rn".data(using: .utf8)!)
return data
}
保存在这里,以备将来有人遇到这个问题时参考。问题是,请求对我的服务器来说太大了,我得到了一个413错误,我错过了…因此,如果将来有人遇到这样的问题,请确保您不会发送过多的数据。我的格式没有问题。