将图像上传到服务器 - Swift 3 [英] Upload image to server - Swift 3
本文介绍了将图像上传到服务器 - Swift 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将图像作为参数与我的请求一起发送。
我使用下面的代码来调用我的POST请求,但我不知道如何将图像附加到正文中。
I want to send an image as a parameter along with my request. I have used the code below to call my POST request but I don't know how to append image to the body.
我通过以下代码获取图像图像选择器如下:
I am getting the image through image picker as follows:
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
我的请求形成如下
var request = URLRequest(url: URL(string: "")!) // link removed
request.httpMethod = "POST"
let postString = "user_id=\(userId)&image=\(image)"
request.httpBody = postString.data(using:.utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
return
}
do {
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? AnyObject
if let parseJSON = json {
print("resp :\(parseJSON)")
}
} catch let error as NSError {
print("error : \(error)")
}
}
task.resume()
我是Swift的新手。我通过multipart / form-data看到了这个,但是我自己无法实现它。我不想以base 64格式对其进行编码。请帮帮我。
I am new to Swift. I have seen this through multipart/form-data but unable to implement it myself. I do not want to encode it in base 64 format. Please help me in this.
推荐答案
我使用以下结构发送图片:
I use the following structure for sending images:
func createRequestBodyWith(parameters:[String:NSObject], filePathKey:String, boundary:String) -> NSData{
let body = NSMutableData()
for (key, value) in parameters {
body.appendString(string: "--\(boundary)\r\n")
body.appendString(string: "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString(string: "\(value)\r\n")
}
body.appendString(string: "--\(boundary)\r\n")
var mimetype = "image/jpg"
let defFileName = "yourImageName.jpg"
let imageData = UIImageJPEGRepresentation(yourImage, 1)
body.appendString(string: "Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(defFileName)\"\r\n")
body.appendString(string: "Content-Type: \(mimetype)\r\n\r\n")
body.append(imageData!)
body.appendString(string: "\r\n")
body.appendString(string: "--\(boundary)--\r\n")
return body
}
func generateBoundaryString() -> String {
return "Boundary-\(NSUUID().uuidString)"
}
extension NSMutableData {
func appendString(string: String) {
let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
append(data!)
}
然后在你的函数中你创建这样的体:
Then in your function you create body like this:
request.httpBody = self.createRequestBodyWith(parameters:yourParamsDictionary, filePathKey:yourKey, boundary:self.generateBoundaryString)
这篇关于将图像上传到服务器 - Swift 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文