使用swift 4使用Multi part & Alamofire上传图片到服务器。

问题描述 投票:0回答:2

我想用alamofire把照片从图库上传到服务器上,这样我怎么能用postman上传呢?

https:/drive.google.comfiled1TYb8ao2KiCCK74BGZPFLdO64xhxd54Yvview?usp=分享。

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()`
ios swift alamofire postman nsurlsession
2个回答
0
投票

我想你也需要用Almaofire上传多部分数据。

见此

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
        }
    }

0
投票

首先,直接存储图片是不好的做法,通常建议存储图片的链接,并使用SDWebImage或Kingfisher等库来传递Image URL。

然后,在向服务器发送数据时,你使用一个 Alamofire.request..... 那么你的请求类型应该是 .post.put

试试,看看是否有效。

© www.soinside.com 2019 - 2024. All rights reserved.