swift - 向分段上传添加自定义自定义参数
问题描述
我试图将图像发送到服务器,但它不断向我抛出 400 错误。我的猜测是它在体内。但是邮递员的请求获得了成功。
我的代码如下
/*****Multipart Upload*********/
func uploadImage(paramName: String, fileType: String, image: UIImage,id:String,comepletion:@escaping ()->Void,failure:@escaping (String)->Void) {
let url = URL(string: "https:someURL")
let boundary = UUID().uuidString
let session = URLSession.shared
var urlRequest = URLRequest(url: url!)
urlRequest.httpMethod = "POST"
urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
urlRequest.setValue(id, forHTTPHeaderField: "some_id")
// Add the image data to the raw http request data
data.append("\r\n--\(boundary)\r\n".data(using: .utf8)!)
//I guess the issue is in the bellow line since I'm
// supposed to send a param called "files" as per the postman screenshot
data.append("Content-Disposition: form-data; name=\"\(paramName)\"; filename=\"\(fileType)\"\r\n".data(using: .utf8)!)//Issue is here
data.append("Content-Type: image/png\r\n\r\n".data(using: .utf8)!)
data.append(image.pngData()!)
data.append("\r\n--\(boundary)--\r\n".data(using: .utf8)!)
// Send a POST request to the URL, with the data we created earlier
session.uploadTask(with: urlRequest, from: data, completionHandler: { responseData, response, error in
if error == nil {
let jsonData = try? JSONSerialization.jsonObject(with: responseData!, options: .allowFragments)
if let json = jsonData as? [String: Any] {
print(json)
}
// comepletion()
}else {
failure(error?.localizedDescription ?? "")
}
}).resume()
}
解决方案
看来你迷路Content Length
了urlRequest
尝试添加:
urlRequest.setValue(String(data.count), forHTTPHeaderField: "Content-Length")
推荐阅读
- python - 如何为二元神经网络编写预测函数?我想使用 4 个变量进行是/否预测
- python - 如何使用 GPU 运行程序?
- javascript - 提取转发的域名并使用 JavaScript 将结果输出到 html 中?
- kdb - kdb+ HTTP 响应中的 CORS
- build - Chromium 构建在 obj/services/network/network_service/preflight_controller.obj 失败
- azure-data-factory - Azure 数据工厂存储事件触发器 - 身份验证
- c++ - pthread_create() 似乎泄漏内存
- python - 我希望这段代码在现有的 xlsx 中创建一个新工作表,而不是创建一个新文件
- powerquery - Power Query - 如何在分隔符后提取
- python - Python“in”语句是循环吗?