使用Swift 4将图像上传到服务器

时间:2019-02-10 21:51:11

标签: ios swift alamofire postman nsurlsession

我正尝试使用alamofire将照片从画廊上传到服务器,这又如何使用邮递员上传

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

,此代码是我的,但失败了,没有上传图片, 当尝试从邮递员生成代码时,它也给我错误,我听不懂代码,这是邮递员的代码

`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()`

2 个答案:

答案 0 :(得分:0)

首先,直接存储图片是一种不好的做法,通常建议存储指向图片的链接,并使用SDWebImage或Kingfisher之类的库来传递图片网址

然后,在将数据发送到服务器时,您使用Alamofire.request.....,然后您的请求类型应为.post.put

尝试一下,看看是否可行。

答案 1 :(得分: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
        }
    }