NSURLSession uploadTaskWithRequest with mime type?

1k views Asked by At

I'm trying to upload an image to a cloud storage with NSURLSession.

let data = UIImageJPEGRepresentation(imageAttachment, 1)
NSURLSession.sharedSession().uploadTaskWithRequest(request, fromData: data)

The image has been successfully uploaded, but it seems that the server does not recognize the data as an image. When I checked the content type from the cloud storage's console, it is set as application/octet-stream.

My question: how to specify mime type for file uploaded with NSURLSession?

1

There are 1 answers

0
Andree On

Never mind, I got it.

I need to set the Content-type header with NSMutableURLRequest before passing it in to uploadTaskWithRequest.

let request = NSMutableURLRequest(URL: url)

request.HTTPMethod = Method.PUT.rawValue
request.setValue("image/jpeg", forHTTPHeaderField: "Content-type")

let data = UIImageJPEGRepresentation(imageAttachment, 1)
NSURLSession.sharedSession().uploadTaskWithRequest(request, fromData: data)