使用迅速4上传图像服务器

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

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

我想你也需要使用多数据与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
        }
    }

0
投票

首先,这是不好的做法,店面形象,直接,它往往是明智的存储链接到图像,并使用像SDWebImage或翠鸟库通过图片网址

发送数据然后,当到服务器,您使用的是Alamofire.request.....那么你的请求类型应该是.post.put

试一下,看看它是否工作。

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