使用 URLSession.shared.uploadTask 将图像和参数上传到 API



我正在尝试解决如何使用 swift 将一组参数和图像文件上传到我的 API。

我的代码大致在这一点上:

//parameters
let actualParameters = ["email": myEmail, "token": myToken, "certnbr": certnbr, "title": title, "newCert": newCert, "expires": expires, "expiryDate": expiryDate, "issueDate": issueDate] as! [String : Any]
let parameters = NewCertModel(email: "email")
//create the url with URL
let url = URL(string: "http://127.0.0.1:8000/api/newCertification/")!
//now create the URLRequest object using the url object
var request = URLRequest(url: url)
request.httpMethod = "POST"
let boundary = "Boundary-(UUID().uuidString)"
request.setValue("multipart/form-data; boundary=(boundary)", forHTTPHeaderField: "Content-Type")
request.httpBody = createBody(parameters: params,
boundary: boundary,
data: UIImageJPEGRepresentation(chosenImage, 0.7)!,
mimeType: "image/jpg",
filename: "hello.jpg")
guard let uploadData = try? JSONEncoder().encode(parameters) else {
print("Error Upload Data")
return
}

//new session
URLSession.shared.uploadTask(with: request as URLRequest, from: jsonData as! Data) { (responseData, response, error) in
// Check on some response headers (if it's HTTP)
if let httpResponse = response as? HTTPURLResponse {
switch httpResponse.statusCode {
case 200..<300:
print("Success")
case 400..<500:
print("Request error")
case 500..<600:
print("Server error")
case let otherCode:
print("Other code: (otherCode)")
}
}
// Do something with the response data
if let
responseData = responseData,
let responseString = String(data: responseData, encoding: String.Encoding.utf8) {
print("Server Response:")
print(responseString)
}
// Do something with the error
if let error = error {
print(error.localizedDescription)
}
}
.resume()
}
}

代码并不完美,因为我尝试了很多解决方案,它们现在有点混乱。我能够轻松地将数据传递到我的 api,但文件上传/多部分难倒了我。我发现这方面的资源很难找到而且有限,尤其是来自全职 Android 开发职位。

我可以切换到Alamofire,但我的整个项目还没有使用它。我想等待切换。我轻松地花了 5 个小时尝试组合,甚至显示最轻微的传递数据,但还没有。

这是我的python代码的开始:

if request.method == 'POST':
email = request.POST.get('email')
token = request.POST.get('token')
certnbr = request.POST.get('certnbr')
title = request.POST.get('title')
newCert = request.POST.get('newCert')
expires = request.POST.get('expires')
expirydate = request.POST.get('expiryDate')
issuedate = request.POST.get('issueDate')
picfile = request.FILES.get('image')
data = {}
#get the user
u = Usr.objects.get(email__iexact=email)

一些我没有运气的来源:

fluffy.es - "这个代码对我来说看起来很草率?">

中等文章 - "我在这里找不到参数传递的提示">

堆栈溢出

更多堆栈溢出

进一步堆叠低

令我惊讶的是所有这些来源之间的不一致,只有少数甚至使用uploadTask,而且我阅读了十几个似乎不同的其他来源。最终阿拉莫火是最好的选择吗?苹果为什么不直接采用它呢?整个过程出奇的困难,提前感谢任何帮助。

编辑: 我切换到阿拉莫菲尔,立即变得更容易。

虽然不是我问题的最佳答案,但 Alamofire 代码更干净。所以为了节省任何未来的压力。只需使用阿拉莫火。

阿拉莫火 Github

let ImageData = imageobj.pngData()
let urlReq = URL(string: "http://127.0.0.1:8000/api/newCertification/")!
print("params")
let params : Parameters = ["email": myEmail, "token": myToken, "certnbr": certnbr, "title": title, "newCert": newCert, "expires": expires, "expiryDate": expiryDate as Any, "issueDate": issueDate as Any]
print("time to upload")
Alamofire.upload(multipartFormData: { multipartFormData in
multipartFormData.append(ImageData!, withName: "avatar",fileName: "file.jpg", mimeType: "image/jpg")
for (key, value) in params {// this will loop the 'parameters' value, you can comment this if not needed
multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
}
},
to:urlReq)
{ (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (progress) in
print("Upload Progress: (progress.fractionCompleted)")
})
upload.responseJSON { response in
//completion("success")
}
case .failure(let encodingError):
print(encodingError)
//completion("failed")

}
}

相关内容

  • 没有找到相关文章

最新更新