RussVirtuoso
RussVirtuoso

Reputation: 888

Multipart file upload in Swift

I have a problem in uploading file in a server called jetty.

I have this code for multipart file upload

   func post(url: String,ticketId: String, workLogDecs: String, status: String,img: UIImage){

    var request = NSMutableURLRequest(URL: NSURL(string: "\(baseURL)\(url)")!)


    let imageData = UIImageJPEGRepresentation(img, 1)


    let parameters = ["workLogDesc":"\(workLogDecs)","requestId":"\(ticketId)","status":"\(status)"]

    let boundary = generateBoundaryString()

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





    request.HTTPBody = createBodyWithParameters(parameters, filePathKey: "files", imageDataKey: imageData, boundary: boundary)

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in

        if error != nil {
            println("error=\(error)")

            var userInfo = error.userInfo
            var errorString = userInfo?.description

            println("errorString \(errorString)")
            return

        }

        // You can print out response object
        println("******* response = \(response)")

        // Print out reponse body
        let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
        println("****** response data = \(responseString!)")
    }
    task.resume()
}

And here is my code for creating body with params:

    func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData {

    var body = NSMutableData();

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

    let filename = "test.jpg"

    let mimetype = "image/jpg"

    body.appendString("–\(boundary)\r\n")
    body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
    body.appendString("Content-Type: \(mimetype)\r\n\r\n")
    body.appendData(imageDataKey)
    body.appendString("\r\n")

    body.appendString("–\(boundary)–\r\n")

    return body
}

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

and I use extension :

extension NSMutableData {
func appendString(string: String) {
    let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
    appendData(data!)
}

My problem is the I'm getting an error and saying "Cannot parse Response"

here is my error log:

Error Domain=NSURLErrorDomain Code=-1017 "cannot parse response" UserInfo=0x7ff43a74c850 {NSUnderlyingError=0x7ff43a6b4660 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1017.)", NSErrorFailingURLStringKey=http://192.168.137.160:8082/ws/worklog/new, NSErrorFailingURLKey=http://192.168.137.160:8082/ws/worklog/new, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-1, NSLocalizedDescription=cannot parse response}

Is there wrong in my code. I am new with this multipart file upload. If there is another way to do this please do help me. Thanks.

Upvotes: 2

Views: 4234

Answers (1)

Rob
Rob

Reputation: 438467

It looks like your code may have come from this answer, but a couple of problems were introduced:

  1. Where you are using a single dash, you need two dashes, e.g.:

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

    and

    body.appendString("--\(boundary)\r\n")
    body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
    body.appendString("Content-Type: \(mimetype)\r\n\r\n")
    body.appendData(imageDataKey)
    body.appendString("\r\n")
    
    body.appendString("--\(boundary)--\r\n")
    
  2. Note, be very, very careful about your dashes. The dashes in your question's code samples appear to be en-dashes, not simply hyphens. (Some word processors will replace two hyphens with an en-dash ... it also explains point 1, where that extra hyphen disappeared.)

  3. Also, you do not appear to be setting the HTTPMethod of the request:

    request.HTTPMethod = "POST"
    

This final point is actual source of the error in your question. But you also have to fix the hyphens or else the request will still fail.

Upvotes: 3

Related Questions