ios 将图像上传到服务器 - Swift 3
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41032678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Upload image to server - Swift 3
提问by Mamta
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.
我想将图像作为参数与我的请求一起发送。我使用下面的代码来调用我的 POST 请求,但我不知道如何将图像附加到正文。
I am getting the image through image picker as follows:
我通过图像选择器获取图像如下:
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
My request is formed as below
我的请求形成如下
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()
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.
我是斯威夫特的新手。我已经通过 multipart/form-data 看到了这一点,但无法自己实现。我不想以 base 64 格式对其进行编码。请帮助我。
回答by Elena
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)
回答by Chhaileng
Swift 4.2
斯威夫特 4.2
func uploadImage(paramName: String, fileName: String, image: UIImage) {
let url = URL(string: "http://api-host-name/v1/api/uploadfile/single")
// generate boundary string using a unique per-app string
let boundary = UUID().uuidString
let session = URLSession.shared
// Set the URLRequest to POST and to the specified URL
var urlRequest = URLRequest(url: url!)
urlRequest.httpMethod = "POST"
// Set Content-Type Header to multipart/form-data, this is equivalent to submitting form data with file upload in a web browser
// And the boundary is also set here
urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
var data = Data()
// Add the image data to the raw http request data
data.append("\r\n--\(boundary)\r\n".data(using: .utf8)!)
data.append("Content-Disposition: form-data; name=\"\(paramName)\"; filename=\"\(fileName)\"\r\n".data(using: .utf8)!)
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)
}
}
}).resume()
}
If you have any header to add, you can add it via urlRequest.setValue
method.
如果您有任何标题要添加,您可以通过urlRequest.setValue
方法添加它。
回答by Muhammad Asyraf
Original Thread:
upload image to server using Alamofireanswer by Ekta Padaliya
Upload Image Using AlamoFire
1. Installation guide please follow tutorials
https://github.com/Alamofire/Alamofire
原始主题:
使用 Alamofire 将图像上传到服务器Ekta Padaliya回答
使用 AlamoFire
上传图像
1. 安装指南请按照教程
https://github.com/Alamofire/Alamofire
Language used Swift 4
2. Import AlamoFire Library
使用的语言Swift 4
2. 导入 AlamoFire 库
import Alamofire
3. Create a custom Method.
(can paste this in UIViewController Extension / your UIViewcontroller as new function)
3. 创建自定义方法。
(可以将此粘贴到 UIViewController 扩展/您的 UIViewcontroller 作为新功能)
func uploadImage(img: UIImage){
let ImageData = UIImagePNGRepresentation(img)
let urlReq = "http://apiUrl.php"
let parameters = ["user_id": "useridValue"]//you can comment this if not needed
Alamofire.upload(multipartFormData: { multipartFormData in
multipartFormData.append(ImageData!, withName: "shop_logo",fileName: "file.jpg", mimeType: "image/jpg")
for (key, value) in parameters {// this will loop the 'parameters' value, you can comment this if not needed
multipartFormData.append(value.data(using: String.Encoding.utf8)!, 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
print(response.result.value)
if let dic = response.result.value as? NSDictionary{
//do your action base on Api Return failed/success
}
}
case .failure(let encodingError):
print(encodingError)
}
}
}
Calling the method like so
self.uploadImage(img: image)
像这样调用方法
self.uploadImage(img: 图像)