-3

I am trying to create a multipart request to upload my image. But it's not working as expected. Can some one explain where I am doing wrong.

static func makeImageRequest(_ urlString: String,version:String, method:FYIHTTPMethod,formData:Data?,fileName:String, completionHandler: @escaping (_ dictionary:NSDictionary?, _ error:NSError?) -> Void ) -> URLSessionTask {
    let fullURL:String = "https://" + domain + ":8243/fyi/" + version + "/" + urlString

    let request = NSMutableURLRequest(url: URL(string: fullURL)!)
    request.timeoutInterval = 300
    request.httpMethod = method.rawValue

    request.setValue("multipart/form-data;boundary=*****", forHTTPHeaderField: "Content-Type")
    request.httpBody = formData

    let accessToken = FYISession.sharedInstance.getAccessToken()
    request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")
    request.setValue("application/json", forHTTPHeaderField: "Accept")
    request.setValue(fileName, forHTTPHeaderField: "image")

    let defaultConfigObject:URLSessionConfiguration = URLSessionConfiguration.default
    let defaultSession:URLSession = URLSession(configuration: defaultConfigObject, delegate: FYIURLSessionDelegate(), delegateQueue: OperationQueue.main)

    let task = defaultSession.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
        guard error == nil && data != nil else {   
            DispatchQueue.main.async {
                completionHandler(nil, error as NSError?)
            }
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
            var message = ""

            if let dta = data{
                do {
                    let json = try? JSONSerialization.jsonObject(with:dta, options: JSONSerialization.ReadingOptions.allowFragments) as? NSDictionary
                    message = json??.object(forKey: "message") as? String ?? ""
                }
            }
            let httpError:NSError = NSError(domain: "HTTP", code: httpStatus.statusCode, userInfo: FYIConnection.userInfo(message))
            DispatchQueue.main.async {
                completionHandler(nil, httpError)
            }
            return
        }

        if (data != nil) {
            do {
                let json:NSDictionary = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary
                let api_status:Bool = json.object(forKey: "api_status") as! Bool

                if (api_status){
                    DispatchQueue.main.async {
                        completionHandler(json,nil)
                    }
                }else {
                    let message:String = json.object(forKey: "message") as! String

                    let httpError:NSError = NSError(domain: FYIConnection.bundleIdentifier(), code: FYIError.apiError.rawValue, userInfo: FYIConnection.userInfo(message))
                    DispatchQueue.main.async {
                        completionHandler(nil, httpError)
                    }
                }
            } catch let jsonError as NSError {
                DispatchQueue.main.async {
                    completionHandler(nil,jsonError)
                }
            }
        }else {
            let httpError:NSError = NSError(domain: FYIConnection.bundleIdentifier(), code: 1, userInfo: FYIConnection.userInfo(""))
            DispatchQueue.main.async {
                completionHandler(nil, httpError)
            }
        }
    })
    task.resume()
    return task
}

And the body is

override func createBodyWithParameters(_ parameters: [String: String]?, image: UIImage?, paths: [String]?, boundary: String) -> Data {
    let body = NSMutableData()
    let data = UIImagePNGRepresentation(image!)

    body.appendString("--\(boundary)\r\n")
    body.appendString("Content-Disposition: form-data; name=\"file\"; filename=\"" + (self.txtMobileNumber?.text ?? "") + ".png"  + "\"\r\n")
    body.appendString("\r\n")
    body.append(data!)
    body.appendString("\r\n")
     body.appendString("--\(boundary)--\r\n")
    return body as Data
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
NavodaP
  • 218
  • 3
  • 18
  • check answers for this question https://stackoverflow.com/q/29623187/6080920 or you can also make use of Alamofire – iOS Geek Jun 08 '18 at 04:32

1 Answers1

0

Try to fix body like this:

override func createBodyWithParameters(_ parameters: [String: String]?, image: UIImage?, paths: [String]?, boundary: String) -> Data {
    let body = NSMutableData()
    let mimeType = "image/jpeg"
    let data = UIImagePNGRepresentation(image!)

    body.appendString("--\(boundary)\r\n")
    body.appendString("Content-Disposition: form-data; name=\"file\"; filename=\"" + (self.txtMobileNumber?.text ?? "") + ".png"  + "\"\r\n")
    body.appendString("Content-Type: \(mimeType)\r\n\r\n")
    body.appendString("\r\n")
    body.append(data!)
    body.appendString("\r\n")
    body.appendString("--\(boundary)--\r\n")
    return body as Data
}

Also try to add this:

request.setValue(String(describing: formData.length), forHTTPHeaderField: "Content-Length")