0

I am sending image to server successfully but fileName is showing Nil or [].How to slove this issue. I shared my source code also.

@IBAction func upLoadBtn(_ sender: Any)

{

    let myUrl = NSURL(string: "http://digilegal.neviton.com:8080/Legal-app/uploadGenDoc");
    //let myUrl = NSURL(string: "http://www.boredwear.com/utils/postImage.php");

    let request = NSMutableURLRequest(url:myUrl! as URL)
    request.httpMethod = "POST"


    let obj1:String = String(masterIdStored)
    let obj2:String = String(associateStored)
    let obj3:String = String(associateNameStored)


    print("obj1 is:\(obj1)")
    let param = [
        "masterClientId"  : obj1,
        "uploaderId"      : obj2,
        "uploaderName"    : obj3
    ] as [String : Any]


    print("param is:\(param)")

    let boundary = generateBoundaryString()

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


    let imageData = UIImageJPEGRepresentation(imageView.image!, 1)

    if(imageData==nil)  { return; }

    request.httpBody = createBodyWithParameters(parameters: param as! [String : String], filePathKey: "file", imageDataKey: imageData! as NSData, boundary: boundary) as Data


    // myActivityIndicator.startAnimating();

    let task = URLSession.shared.dataTask(with: request as URLRequest) {
        data, response, error in

        if error != nil {
            print("error=\(error)")
            return
        }

        // You can print out response object
        print("******* response = \(String(describing: response))")

        // Print out reponse body
        let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
        print("****** response data = \(responseString!)")


        let respVO:[RespVo] = Mapper<RespVo>().mapArray(JSONString: responseString! as String)!

        print("responseString = \(respVO)")

        let successResp = respVO[0].response




        let statusResp = "Documents saved successfully"

        if successResp! == (statusResp as NSString) as String {

            DispatchQueue.main.async(execute: { () -> Void in

                //                    self.submitOutlet.isUserInteractionEnabled = false


                let ViewController = self.storyboard?.instantiateViewController(withIdentifier: "CustomSecondAlertViewController") as! CustomSecondAlertViewController

                ViewController.view.backgroundColor = UIColor.black.withAlphaComponent(0.6)

                self.addChildViewController(ViewController)
                self.view.addSubview(ViewController.view)
                self.dismiss(animated: false, completion: nil)

            })


        }

    }

    task.resume()
}


func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData {
    let body = NSMutableData();

    if parameters != nil {
        for (key, value) in parameters! {
            body.appendString(string: "--\(boundary)\r\n")
            body.appendString(string: "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
            body.appendString(string: "\(value)\r\n")
        }
    }



    //let newObj = "manu.jpg"
    //let manuObj = fileNameLabel.text
    body.appendString(string: "--\(boundary)\r\n")

    var mimetype = "image/jpg"

    //let defFileName = fileNameObj



    let imageData = UIImageJPEGRepresentation(imageView.image!, 1)
    print("defFileName is :\(String(describing: imageData))")

    let fnamed = fileNameObj
    print("fnamed is:\(fnamed)")
    body.appendString(string: "Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(String(describing: fnamed))\"\r\n")
    body.appendString(string: "Content-Type: \(mimetype)\r\n\r\n")
    body.append(imageData!)
    body.appendString(string: "\r\n")

    body.appendString(string: "--\(boundary)--\r\n")

    return body
}


func generateBoundaryString() -> String {
    return "Boundary-\(NSUUID().uuidString)"
}


extension NSMutableData {

    func appendString(string: String) {
        let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
        append(data!)
    }
}
Rob
  • 415,655
  • 72
  • 787
  • 1,044
krishna
  • 23
  • 8
  • You say `fileName` is blank, but you supplied `filePathKey` of `file` to the `createBodyWithParameters` method. Make sure that whatever name you're looking for in your web service is the same as the name you supply when building the body. If this is unclear, you might want to show relevant excerpt or spec from your web service, so we can confirm precisely what web service is looking for. – Rob Oct 27 '17 at 09:09
  • By the way, it looks like this code was adapted from https://stackoverflow.com/a/26163136/1271826, but it's worth noting that answer now has Swift 3 rendition that avoids the use of `NSMutableURLRequest`, `NSURL` and `NSData`, which you use above. – Rob Oct 27 '17 at 09:12

0 Answers0