I need to upload a canvas (saved as a png image) via jQuery Ajax. If I upload an image via a multipart form, where the user browses to a file than hits a submit button it works, but I need to capture a canvas and upload the image where the user is not uploading a file, but rather hitting a button to have the canvas converted than uploaded.
Here is an example form submit that uploads a file once a user browses and uploads their file:
<form action="http://myrestservice/endpoint" name="form" id="formId" method="post" enctype="multipart/form-data">
<input type="file" name="File1" size="50" maxlength="50" /><a class="textLabel">*** Upload a file is required</a>
<input type="submit" value="Submit Request">
</form>
This is only to demonstrate that the Web Service works. It states that the type of transfer is Document. I also get a 200 OK response.
If I create a different page with a canvas and add a button to upload the canvas to an image, it states that the type of transfer is xhr. I also get a 200 OK response.
Here is my JavaScript for uploading a canvas once it's converted to an image. What is interesting is that this code gives me a "not found in Access-Control-Allow-Origin header." error, while the regular manual upload does not:
$scope.imageMe = function () {
var canvasImage = document.getElementById("c");
var img = canvasImage.toDataURL("image/png");
var filename = 'Test.png';
var formdata = new FormData();
formdata.append(filename, img);
$.ajax({
url: 'http://myrestservice/endpoint',
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (result) {
console.log("Upload complete!");
},
error: function (error) {
console.log("Something went wrong!");
}
});
}
UPDATE:
I am able to post, but I don't get a response, as I get a cross origin error. The application vendor has replied with:
The page where you want to use the Ajax call, needs to send a correct access-control-allow-origin header. (this needs to be done by the webserver)
How/where do I add this in the AJAX to allow a cross origin call since the Web Service is in another domain?
UPDATE 2:
The vendor has responded with the following requirements. Given this, how do I code my AJAX request to work?
The HTTP POST requests must meet the following requirements:
- The value of the Content-Type header of the HTTP POST request should be, in most cases, multipart/form-data.
- HTTP request parts can be added to the HTTP POST requests to attach data files and/or to add parameters.
- For every HTTP request part that is added to an HTTP POST request, a Content-Disposition header should be present.
- For each data file, the (UTF-8 encoded) file name of the data file should be specified in the corresponding Content-Disposition header.
- For each parameter, the name of the parameter should be specified in the corresponding Content-Disposition header.
- The encoding of the HTTP POST requests should be base64 or no encoding (for example binary, 8bit,…).