使用 swift 上传图片到服务器 4 使用 Multi part & Alamofire
uploading image to server using swift 4 use Multi part & Alamofire
我正在尝试使用 alamofire 将照片从图库上传到服务器,我如何使用 postman
上传照片
https://drive.google.com/file/d/1TYb8ao2KiCCK74BGZPFLdO64xhxd54Yv/view?usp=sharing
func uploadImage(){
var url = "\(BASE_URL)Image/Upload?model=tbl_accounts&model_id=\(AuthService.instance.userID)&model_tag=main"
//url = url.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
guard let imageData = UIImageJPEGRepresentation(imgProfile.image!, 0.4) else {
return
}
Alamofire.upload(imageData, to: URL(string: url)!, method: .post, headers: HeaderForLoggedUser).responseJSON { (response) in
if let JSON = response.result.value as? NSDictionary {
print(JSON)
} else {
let message = response.result.error != nil ? response.result.error!.localizedDescription : "Unable to communicate."
print(message)
}
}}
这个代码是我的,但是它失败了,没有上传图片,
当尝试从 postman 生成代码时,它也给我错误,我无法理解代码,这是来自 post man
的代码
`let headers = [
"content-type": "multipart/form-data; boundary=----
WebKitFormBoundary7MA4YWxkTrZu0gW",
"Content-Type": "application/x-www-form-urlencoded",
"APP_KEY": "{APP_KEY}",
"AUTH_KEY": "{AUTH_KEY}",
"Cache-Control": "no-cache",
]
let parameters = [
[
"name": "img",
"fileName": "C:\Users\Admin\Downloads\IMG-20190130-WA0006(1).jpg"
]
]
let boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW"
var body = ""
var error: NSError? = nil
for param in parameters {
let paramName = param["name"]!
body += "--\(boundary)\r\n"
body += "Content-Disposition:form-data; name=\"\(paramName)\""
if let filename = param["fileName"] {
let contentType = param["content-type"]!
let fileContent = String(contentsOfFile: filename, encoding:
String.Encoding.utf8)
if (error != nil) {
print(error)
}
body += "; filename=\"\(filename)\"\r\n"
body += "Content-Type: \(contentType)\r\n\r\n"
body += fileContent
} else if let paramValue = param["value"] {
body += "\r\n\r\n\(paramValue)"
}
}
let request = NSMutableURLRequest(url: NSURL(string:
"https://nearyouweb.com/Api/v1/en/image/upload?
model=tbl_accounts&model_id=8")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest,
completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse)
}
})
dataTask.resume()`
首先,直接存储图像是不好的做法,通常建议将 link 存储到图像并使用像 SDWebImage 或 Kingfisher 这样的库来传递图像 URL
然后向服务器发送数据时,您使用Alamofire.request.....
然后您的请求类型应该是.post
或.put
试一试,看看是否有效。
我认为您还需要使用 Alamofire 上传的多部分数据
看到这个
let parameters = [
// List Parameter here if any
]
Alamofire.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(imageData, withName: "photo_path", fileName: "swift_file.jpeg", mimeType: "image/jpeg")
for (key, value) in parameters {
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
}
}, to:"yourURL")
{ (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (progress) in
//Print progress
})
upload.responseJSON { response in
//print response.result
}
case .failure(let encodingError):
//print encodingError.description
}
}
我正在尝试使用 alamofire 将照片从图库上传到服务器,我如何使用 postman
上传照片https://drive.google.com/file/d/1TYb8ao2KiCCK74BGZPFLdO64xhxd54Yv/view?usp=sharing
func uploadImage(){
var url = "\(BASE_URL)Image/Upload?model=tbl_accounts&model_id=\(AuthService.instance.userID)&model_tag=main"
//url = url.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
guard let imageData = UIImageJPEGRepresentation(imgProfile.image!, 0.4) else {
return
}
Alamofire.upload(imageData, to: URL(string: url)!, method: .post, headers: HeaderForLoggedUser).responseJSON { (response) in
if let JSON = response.result.value as? NSDictionary {
print(JSON)
} else {
let message = response.result.error != nil ? response.result.error!.localizedDescription : "Unable to communicate."
print(message)
}
}}
这个代码是我的,但是它失败了,没有上传图片, 当尝试从 postman 生成代码时,它也给我错误,我无法理解代码,这是来自 post man
的代码`let headers = [
"content-type": "multipart/form-data; boundary=----
WebKitFormBoundary7MA4YWxkTrZu0gW",
"Content-Type": "application/x-www-form-urlencoded",
"APP_KEY": "{APP_KEY}",
"AUTH_KEY": "{AUTH_KEY}",
"Cache-Control": "no-cache",
]
let parameters = [
[
"name": "img",
"fileName": "C:\Users\Admin\Downloads\IMG-20190130-WA0006(1).jpg"
]
]
let boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW"
var body = ""
var error: NSError? = nil
for param in parameters {
let paramName = param["name"]!
body += "--\(boundary)\r\n"
body += "Content-Disposition:form-data; name=\"\(paramName)\""
if let filename = param["fileName"] {
let contentType = param["content-type"]!
let fileContent = String(contentsOfFile: filename, encoding:
String.Encoding.utf8)
if (error != nil) {
print(error)
}
body += "; filename=\"\(filename)\"\r\n"
body += "Content-Type: \(contentType)\r\n\r\n"
body += fileContent
} else if let paramValue = param["value"] {
body += "\r\n\r\n\(paramValue)"
}
}
let request = NSMutableURLRequest(url: NSURL(string:
"https://nearyouweb.com/Api/v1/en/image/upload?
model=tbl_accounts&model_id=8")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest,
completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse)
}
})
dataTask.resume()`
首先,直接存储图像是不好的做法,通常建议将 link 存储到图像并使用像 SDWebImage 或 Kingfisher 这样的库来传递图像 URL
然后向服务器发送数据时,您使用Alamofire.request.....
然后您的请求类型应该是.post
或.put
试一试,看看是否有效。
我认为您还需要使用 Alamofire 上传的多部分数据
看到这个
let parameters = [
// List Parameter here if any
]
Alamofire.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(imageData, withName: "photo_path", fileName: "swift_file.jpeg", mimeType: "image/jpeg")
for (key, value) in parameters {
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
}
}, to:"yourURL")
{ (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (progress) in
//Print progress
})
upload.responseJSON { response in
//print response.result
}
case .failure(let encodingError):
//print encodingError.description
}
}