I'm trying to get an image uploaded to a RESTful web api and I'm getting a HTTP status 415 (unsupported media type). The strange thing is I did have it working the other day and i'm not to sure what i've changed to make it stop accepting the POST request.
My swift code:
func uploadImage(image: UIImage, userId: String, completion: () -> Void) {
parameters["userId"] = userId
let imageData = UIImageJPEGRepresentation(image, 70)
let urlRequest = urlRequestWithComponents(myUrl, parameters: parameters, imageData: imageData!)
Alamofire.upload(urlRequest.0, data: urlRequest.1)
.responseJSON { (response) in
print(response)
if let result = response.result.value as? Dictionary<String, String>{
print("have a result from uploading!")
print(result)
if let result = result["success"] {
if (result == "true") {
completion()
}
}
}
}
}
func urlRequestWithComponents(urlString:String, parameters:Dictionary<String, String>, imageData:NSData) -> (URLRequestConvertible, NSData) {
// create url request to send
let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: urlString)!)
mutableURLRequest.HTTPMethod = Alamofire.Method.POST.rawValue
let boundaryConstant = "myRandomBoundary12345";
let contentType = "multipart/form-data"
mutableURLRequest.setValue(contentType, forHTTPHeaderField: "Content-Type")
// create upload data to send
let uploadData = NSMutableData()
// add image
uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
uploadData.appendData("Content-Disposition: form-data; name=\"file\"; filename=\"file.png\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
uploadData.appendData("Content-Type: image/png\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
uploadData.appendData(imageData)
// add parameters
for (key, value) in parameters {
uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
uploadData.appendData("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".dataUsingEncoding(NSUTF8StringEncoding)!)
}
uploadData.appendData("\r\n--\(boundaryConstant)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
// return URLRequestConvertible and NSData
return (Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: nil).0, uploadData)
}
And here is what my Jersey Rest service accepts for that url:
@POST
@Path("/uploadImage")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
public String uploadImage(FormDataMultiPart form) throws IOException
{
//do stuff
}
Its driving me crazy trying to figure out what is going wrong, any help is muchly appreciated!