I've been experimenting with the FormData
API. You can check out the fiddle I'm working on here - my goal is to embed blobs into my form and submit it via AJAX.
//ic0 and tc0 represent canvases
//image0 and thumb0 are file inputs
function ajaxSubmit(){
var fd = new FormData(document.forms[0]);
ic0.toBlob(
function(blob){
fd.set("image0", blob, "image0.jpg");
}, "image/jpeg", 0.7);
tc0.toBlob(
function(blob){
fd.set("thumb0", blob, "thumb0.jpg");
}, "image/jpeg", 0.7);
var xhr = new XMLHttpRequest();
xhr.open("POST", "/ajax-upload/", true);
xhr.send(fd);
}
The behavior of browsers seems a bit peculiar:
Chrome 50 (in Ubuntu)
Encounters an issue, displaying:
Failed blob:https%3A//fiddle.jshell.net/uuid4 to load resource: the server responded with 404
I thought FormData.set()
was now supported? It works with non-blobs, right?
Firefox 46 (in Ubuntu)
If the FormData()
object is not initialized with an existing DOM object containing necessary file inputs, it doesn't seem to work as expected. FormData.set()
doesn't appear to function properly with file inputs and blobs (despite calling
fd.set("thumb0", blob, "thumb0.jpg")
, resulting in thumb0
being null in the payload. By checking console.log(fd.get("thumb0"))
immediately after setting, you'll notice that the value is indeed set. Additionally, the payload for image0
turns out to be the original image instead of the resized canvas image.
It's inconvenient not being able to customize multipart FormData
using JavaScript. As someone relatively new to JavaScript, am I missing something crucial here, or could these browsers potentially have issues supporting the FormData
API correctly? How do I correctly submit image0
and thumb0
in my fiddle?
Edit: Deciding to prioritize this. I'm aware of larger jQuery-dependent libraries like blueimp, but I prefer transmitting data as file inputs rather than basing it in base64 (and avoiding jQuery altogether). For this project, I only need support for the latest versions of Chrome and Firefox and hope to maintain clean code as suggested by the FormData
API. Can anyone successfully extract an image from a canvas and include it in the POST payload as a file? Ideally, I'd like to access it in request.FILES
within Django.