使用 Alamofire 将图像上传到服务器在 swift iOS 中放置请求

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

我从图像选择器中选择了图像,然后将其大小减小到 1 MB 以下,然后尝试使用以下功能实现上传,但没有成功。

请求正文架构应如上图所示。

请建议使用提到的请求正文架构上传图像的正确方法。

    //Method for uploading image
func uploadImageFile(url:String, imageData: Data, fileName: String, completion: @escaping (Bool) -> Void) {
    let headers = configureImageCurrentSession()
    AF.upload(
        multipartFormData: { multipartFormData in
            
            multipartFormData.append(imageData, withName: fileName)
        },
        to: url, method: .put , headers: headers)
        .response { resp in
            print(resp)
            print("Data::: \(String(data: resp.data ?? Data(), encoding: .utf8))")
            completion(true)
        }
}

根据请求主体架构需要传递 content 作为 object 需要一个如何将其包含在请求中。

在完成响应中,它打印如下。

Data::: Optional("{"statusCode":400,"error":"Bad Request","message":"part content is missing"}")

ios swift objective-c xcode alamofire
1个回答
0
投票

检查下面的代码

 func imageupload(_ url: String, _ imageData: Data,_ parameters: NSDictionary, completion: @escaping (NSDictionary) -> Void) {
    // Set url here
    guard let url = URL(string: url) else {
        return
    }
    
    var urlRequest = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 10.0 * 1000)
    urlRequest.httpMethod = "PUT"
    urlRequest.addValue("application/json", forHTTPHeaderField: "Accept")
    urlRequest.addValue("your autho token", forHTTPHeaderField: "Authorization")
    
    // Now Execute
    AF.upload(multipartFormData: { multiPart in
        for (key, value) in parameters {
            if let temp = value as? String {
                multiPart.append(temp.data(using: .utf8)!, withName: key as! String)
            }
            if let temp = value as? Int {
                multiPart.append("\(temp)".data(using: .utf8)!, withName: key as! String)
            }
            if let temp = value as? NSArray {
                temp.forEach({ element in
                    let keyObj = key as! String + "[]"
                    if let string = element as? String {
                        multiPart.append(string.data(using: .utf8)!, withName: keyObj)
                    } else
                    if let num = element as? Int {
                        let value = "\(num)"
                        multiPart.append(value.data(using: .utf8)!, withName: keyObj)
                    }
                })
            }
        }
        multiPart.append(imageData, withName: "image", fileName: "file.png", mimeType: "image/png")
    }, with: urlRequest)
        .uploadProgress(queue: .main, closure: { progress in
            //Current upload progress of file
            print("Upload Progress: \(progress.fractionCompleted)")
        })
        .responseJSON(completionHandler: { data in
            print("data = ",data)
            
            switch data.result
            {
            case .failure(let error):
                if let data = data.data {
                    print("Print Server Error: " + String(data: data, encoding: String.Encoding.utf8)!)
                }
                print(error)
                
            case .success(let value):
                
                print(value)
            }
            
            switch data.result {
            case .success(_):
                do {
                    let dictionary = try JSONSerialization.jsonObject(with: data.data!, options: .fragmentsAllowed) as! NSDictionary
                    
                    print("Success!")
                    print(dictionary)
                }
                catch {
                    // catch error.
                    print("catch error")
                }
                break
            case .failure(_):
                print("failure")
                break
            }
        }).cURLDescription { description in
            print(description)
        }
}
© www.soinside.com 2019 - 2024. All rights reserved.