0

enter image description here

I have picked image from image picker and then reduced it's size to below 1 MB and then trying to upload with below function implementation but it was not successful.

Request body schema should be as mentioned in the above image.

please suggest proper way of uploading image with mentioned request body schema.

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

According to the request body schema need to pass content as object required one how to include that as well in the request.

In completion response it prints as like this.

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

HangarRash
  • 7,314
  • 5
  • 5
  • 32
iOSDude
  • 274
  • 2
  • 25
  • "but it was not successful." Could you define that? What's the output of `print(resp)`? Do you have a response from the server that you might parse? Like `String(data: resp.data ?? Data(), encoding: .utf8)`? – Larme Feb 23 '22 at 00:10
  • Response status code and error is 401. Data::: Optional("{\"statusCode\":400,\"error\":\"Bad Request\",\"message\":\"part content is missing\"}") – iOSDude Feb 23 '22 at 03:37
  • one thing you can do is change the BackEnd to take image as String. Other solution is keep like it is and try, https://stackoverflow.com/a/33012955/10505343 – Wimukthi Rajapaksha Feb 23 '22 at 03:56

1 Answers1

0

Check this below code

 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)
        }
}
Community
  • 1
  • 1
Sasi
  • 1
  • 1
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 23 '22 at 08:26