Search code examples
swift3image-uploadinginternal-server-errorhttp-status-code-500

Swift 3: Server Error 500 on uploading Image


I am trying to upload the image to the server but getting 500 server error. Below is my code:

public func uploadImage(docID: String, image: UIImage, comments: String, onCompletion: @escaping APIPostCallResponse)
{
    self.postCallback = onCompletion

    let u = "\(IMAGE_UPLOAD)\(docID)&comment=\(comments)"
    let urlString: String = u.replacingOccurrences(of: " ", with: "%20")

    print(urlString)

    guard let url = URL(string: urlString) else
    {
        return
    }

    let imageData = UIImageJPEGRepresentation(image, 1)



    if imageData != nil
    {
        let request = NSMutableURLRequest(url: url)
        request.httpMethod = "POST"

        let loginString = String(format: "%@:%@", getUsername()!, getPassword()!)
        let loginData = loginString.data(using: String.Encoding.utf8)!
        let base64LoginString = loginData.base64EncodedString()

        request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")

        let fieldName = "FieldName"

        let uniqueId = ProcessInfo.processInfo.globallyUniqueString
        let boundary = "------iOS\(uniqueId)"

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

        let postBody:NSMutableData = NSMutableData()
         var postData:String = String()

        postData += "--\(boundary)\r\n"
        postData += "Content-Disposition: form-data; name=\"\(fieldName)\"; filename=\"\(Int64(Date().timeIntervalSince1970*1000)).jpg\"\r\n"
        postData += "Content-Type: image/jpeg\r\n\r\n"
        postBody.append(postData.data(using: String.Encoding.utf8)!)
        postBody.append(imageData!)
        postData = String()
        postData += "\r\n"
        postData += "\r\n--\(boundary)--\r\n"
        postBody.append(postData.data(using: String.Encoding.utf8)!)

        request.httpBody = NSData(data: postBody as Data) as Data

        let session = URLSession.shared

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

            let httpResponse = response as! HTTPURLResponse

            if httpResponse.statusCode >= 200 && httpResponse.statusCode < 300
            {
                guard let _:Data = data, let _:URLResponse = response , error
                    == nil else {
                        print("error")
                        return
                }

                self.uploadSuccessful()
            }
            else
            {
                let dataString = String(data: data!, encoding:
                    String.Encoding(rawValue: String.Encoding.utf8.rawValue))
                print(dataString!)
                self.uploadFailed(errorMessage: dataString!)
            }     
        }
        task.resume()
    }
    else
    {
        uploadFailed(errorMessage: "No Data")
    }

}

Here is the response I am getting back:

<NSHTTPURLResponse: 0x7a6e4c80> { URL: http://url.com/images/up?docType=Image&docId=100&comment=Jhsgfdhsj } { status code: 500, headers {
"Cache-Control" = "no-cache";
Connection = "keep-alive";
"Content-Length" = 36;
"Content-Type" = "application/json; charset=utf-8";
Date = "Mon, 30 Jan 2017 16:17:22 GMT";
Expires = "-1";
Pragma = "no-cache";
Server = "Microsoft-IIS/8.5";
"X-AspNet-Version" = "4.0.30319";
"X-Powered-By" = "ASP.NET";
} }

The URL is correct as the same url is working on Android fine. I don't even know what is wrong with code. Please help me to solve it.


Solution

  • Compression was the problem here. I had to change the compression of image to 0.5 from 1.