如何使用JSON格式的参数在byteArray中发送图像iOS swift4
我是iOS的初学者,我对编程的了解要少得多。现在,在我的项目中,我遇到了一个任务,我必须将创建的用户的数据与上传的相机图像或照片库一起发送。事实上,我不知道该怎么做,我搜索了互联网,stackoverflow和其他一些关于如何在swift4中发送带有参数的图像的博客,并试图理解这个过程,我已经尝试了一周,我不知道还能做什么。我在这里发布我的代码:如何使用JSON格式的参数在byteArray中发送图像iOS swift4,ios,http-post,alamofire,swift4,image-uploading,Ios,Http Post,Alamofire,Swift4,Image Uploading,我是iOS的初学者,我对编程的了解要少得多。现在,在我的项目中,我遇到了一个任务,我必须将创建的用户的数据与上传的相机图像或照片库一起发送。事实上,我不知道该怎么做,我搜索了互联网,stackoverflow和其他一些关于如何在swift4中发送带有参数的图像的博客,并试图理解这个过程,我已经尝试了一周,我不知道还能做什么。我在这里发布我的代码: @IBAction func createAccountTapped(_sender: UIButton!) { guard le
@IBAction func createAccountTapped(_sender: UIButton!) {
guard let image = profileImgView.image else {return}
let imageData = UIImageJPEGRepresentation(image, 0.7)
print(imageData!)
let byteArray = Array(imageData!)
let updateProfileUrl = "http://isit.beetlerim.com/api/UsersAPI/UpdateUserProfile"
let parameters = [
"UserName":userNameTF.text!,
"Password":passwordTF.text!,
"UserTypeId":2,
"profilePic":"\(arc4random()).jpg",
"profileImage":byteArray,
"DOB":dateOfBirthTF.text!,
"PhoneNumber":phoneNumberTF.text!,
"Mobile":phoneNumberTF.text!,
"Email":emailAddressTF.text!,
"AddressLine1":address1TF.text!,
"AddressLine2":address2TF.text!,
"City":cityTF.text!,
"State":stateTF.text!,
"Country":countryTF.text!,
"ZipCode":zipcodeTF.text!
] as [String : Any]
let jsonData = try? JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
print(jsonData!)
// create post request
let url = URL(string: updateProfileUrl)!
var request = URLRequest(url: url)
request.httpMethod = "POST"
// insert json data to the request
request.httpBody = jsonData
request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accpet")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print(error?.localizedDescription ?? "No data")
return
}
let responseJSON = try? JSONSerialization.jsonObject(with: data, options: .allowFragments )
if let responseJSON = responseJSON as? [String: Any] {
print(responseJSON)
}
}
task.resume()
}
我收到响应:[“消息”:发生错误。]
}
我也尝试过很多其他的方法。。他们都不工作。。
请帮帮我,伙计们:首先,您需要确保图像大小小于服务器端的最大值,这是服务器可能会告诉您的一种方式,但您仍然需要使用服务器端对其进行调试。比如说,它通常被限制为最大2MB 因此,您需要先调整其大小,然后将其转换为base64,但这不是上传图像的首选方式,因为它会将传输的数据大小增加33%。服务器端应该使用
多部分/表单数据
,因为这是通过HTTP传输二进制数据的标准方式。但你看:
let imageResized = image.resizeWith(percentage: 0.1)
let base64 = imageResized?.toBase64()
您需要使用以下扩展:
extension UIImage {
func resizeWith(percentage: CGFloat) -> UIImage? {
let imageView = UIImageView(frame: CGRect(origin: .zero, size: CGSize(width: size.width * percentage, height: size.height * percentage)))
imageView.contentMode = .scaleAspectFit
imageView.image = self
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
imageView.layer.render(in: context)
guard let result = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
UIGraphicsEndImageContext()
return result
}
}
extension UIImage {
func toBase64() -> String? {
let imageData : NSData = UIImageJPEGRepresentation(self, 1.0)! as NSData
return imageData.base64EncodedString(options: NSData.Base64EncodingOptions.lineLength64Characters)
}
}
最后,通过以下方式发送参数:
let parameters = [
"UserName":userNameTF.text!,
"Password":passwordTF.text!,
"UserTypeId":2,
"profilePic":"\(arc4random()).png",
"profileImage":base64!,
"DOB":dateOfBirthTF.text!,
"PhoneNumber":phoneNumberTF.text!,
"Mobile":phoneNumberTF.text!,
"Email":emailAddressTF.text!,
"AddressLine1":address1TF.text!,
"AddressLine2":address2TF.text!,
"City":cityTF.text!,
"State":stateTF.text!,
"Country":countryTF.text!,
"ZipCode":zipcodeTF.text!
] as [String : Any]
希望这能奏效 错误消息明确表示不支持“multipart/form data”,您仍然尝试使用
multipartFormData
?最好检查API规范。@OOper您能解释一下,如何以application/json格式发送带有参数的图像。我们需要在http头中设置图像的内容类型,即png或jpeg@VIP-devi是以标题:[“内容类型”:“application/json”]
的形式在那里完成的,仍然没有结果。@OOper我想知道我是否可以询问我们的服务器端开发人员他们正在接受什么样的数据,并确保我以这种方式发送数据。@Aaoli OMG!!!那是一根该死的绳子。。成功了,非常感谢你。我会欠你的债。。。