Cordova multiple image upload with File Transfer - javascript

I'm on a cordova and jquery mobile project.
I've been able to upload one image with file transfer plugin.
Now i try to upload 2 or 3 images following.
here is the html code:
<label for="image">Pictures:</label>
Get first picture<br>
Get second picture<br>
Get third picture<br>
<img id="image1" style="display:none;width:25%;">
<img id="image2" style="display:none;width:25%;">
<img id="image3" style="display:none;width:25%;">
<label for="title">Title</label>
<input data-clear-btn="true" name="title" id="title" value="" type="text">
<input value="Continue" type="submit" id="adButton">
here is jquery code:
multi_upload(user_id);
function multi_upload(user_id) {
var image1 = "image1";
var image2 = "image2";
var image3 = "image3";
if($('#image2').prop('src') == ''){
// upload one file
upload(user_id, image1, "true");
}
if($('#image3').prop('src') == ''){
// upload two files
upload(user_id, image1, "false");
upload(user_id, image2, "true");
}
if($('#image3').prop('src') != ''){
// upload three files
upload(user_id, image1, "false");
upload(user_id, image2, "false");
upload(user_id, image3, "true");
}
}
function upload(user_id, imagesrc, final) {
var img = '';
var imageURI = '';
img = document.getElementById(imagesrc);
imageURI = img.src;
console.log("[imageURI] "+imageURI);
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
var params = {};
params.timestamp = Math.round(+new Date()/1000);
params.public_token = localStorage.getItem("token_public");
params.hash = SHA1(params.timestamp+localStorage.getItem("token_private"));
params.user_id = user_id;
options.params = params;
options.chunkedMode = false;
var ft = new FileTransfer();
if(final == "true"){
ft.upload(imageURI, "http://www.example.com/api/index.php/privates/upload", finalwin, fail, options);
}else{
ft.upload(imageURI, "http://www.example.com/api/index.php/privates/upload", win, fail, options);
}
}
If i upload two files for example, the code will upload two times the last selected picture. the console give me the imageURI who looks like this:
file:///storage/sdcard0/Android/data/fr.myproject.propro/cache/modified.jpg?1418726649440:500
I suppose that is a temporary file, so i presume when i select the last file, it delete the previous one... how can i find the real path of this images?

We recently sat with the same problem, and found that the cache file (project/cache/modified.jpg) was overriden (as you note) by a new selection, although FileTransfer.upload seems to treat it as two different files (presumably due to the ?-parameter) and thus uploads it twice.
As a workaround, we ended up renaming the files to include a timestamp before the name, such that modified.jpg?1418726649440 becomes 1418726649440modified.jpg, prior to uploading them:
function renameFile(src, callback) {
var d = new Date();
//find the FileEntry for the file on the device
window.resolveLocalFileSystemURL(src, function(fileEntry) {
//get the parent directory (callback gives a DirectoryEntry)
fileEntry.getParent(function(parent) {
//rename the file, prepending a timestamp.
fileEntry.moveTo(parent, d.getTime() + fileEntry.name, function(s) {
//Callback with the new URL of the file.
callback(s.nativeURL);
}, function(error) {
alert('Error on moving file!');
callback(src); //Fallback, use the src given
});
}, function(error) {
alert('Error on getting parent!');
callback(src); //Fallback
});
}, function(error) {
alert('Error on resolveLocalFileSystemURI!');
callback(src); //Fallback
});
}
With src being the imageURI (i.e. path of the file), and callback being the function that uploads the file. (I should note that we're not entirely sure if we need the getParent call, as one could presumably get the DirectoryEntry by parsing src, but better safe than sorry)
NOTE: This requires the File plugin, and, depending both on your version of Cordova and File, may need to be edited somewhat (as the API has changed a little between versions).

Related

Make HTML5 FileReader working with heic files

When reading a file from the input element by the FileReader api it works, but my android device also allows sending files and it seems to send heic files anyway which then results in an empty image without any errors in the console. Also the orientation is wrong when getting an image directly from the camera. I just found heavy librarys to implement and i am looking for a smarter solution.
JavaScript
function previewFile( e ) {
var preview = document.getElementById('usersProfilePicture');
var file = e.files[0];
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
}
if (file) {
reader.readAsDataURL(file);
} else {
preview.src = "";
}
}
HTML5
<form>
<label>
<input id="uploadProfilePicture" name=file type=file accept="image/jpg, image/jpeg, image/png, image/gif, image/bmp">
</label>
</form>
There are no error messages at all. Firefox, Chrome both on desktop and android allow .heic files no matter what accept attribute i set.
worst solution: deny acceptance of .heic files
best solution: make fileReader work with .heic files.
in between solution: detect heic and convert it to jpeg, clientside.
The answer above explains this very well but for anyone looking for another example I have slightly modified the example from Heic2Any (https://alexcorvi.github.io/heic2any/)
<input type="file" id="heic" onchange="convertHEIC(event)">
async function convertHEIC (event){
let output = document.getElementById('output');
//if HEIC file
if(event.target.files[0] && event.target.files[0].name.includes(".HEIC")){
// get image as blob url
let blobURL = URL.createObjectURL(event.target.files[0]);
// convert "fetch" the new blob url
let blobRes = await fetch(blobURL)
// convert response to blob
let blob = await blobRes.blob()
// convert to PNG - response is blob
let conversionResult = await heic2any({ blob })
// convert to blob url
var url = URL.createObjectURL(conversionResult);
document.getElementById("target").innerHTML = `<a target="_blank" href="${url}"><img src="${url}"></a>`;
}
};
I have a workaround for this issue for now by using the library heic2any
(https://github.com/alexcorvi/heic2any)
check to see if file from input is .heic, then use library like so:
heic2any({
// required: the HEIF blob file
blob: file,
// (optional) MIME type of the target file
// it can be "image/jpeg", "image/png" or "image/gif"
// defaults to "image/png"
toType: "image/jpeg",
// conversion quality
// a number ranging from 0 to 1
quality: 0.5
})
I wrap this call in a promise and then pass the result to the file reader:
// uploadHEIC is a wrapper for heic2any
uploadHEIC(heicFile).then(function (heicToJpgResult) {
var reader = new Filereader();
reader.onload = function () {
// Do what you want to file
}
reader.readAsArrayBuffer(heicToJpgResult);
}
A few things to note to get this working properly.
First, in windows the assigned mime type for heic and heif is blank. Not sure when this bug will get fixed, but for now you can't rely on mime type in your scripts or input tag. I needed to add the heic and heif file extensions in the accept parameter of my input tag:
<input type="file" accept="image/*,.heic,.heif" />
and in my script I created a function to check the file extension for heic and heif if mime type was blank.
function isHEIC(file) { // check file extension since windows returns blank mime for heic
let x = file.type ? file.type.split('image/').pop() : file.name.split('.').pop().toLowerCase();
return x == 'heic' || x == 'heif';
}
Also, heic2any is pretty large (even if minified and compressed). I decided to load it dynamically only when needed.
function loadScript(url, callback) {
var script = document.querySelectorAll('script');
for (var i = 0; i < script.length; i++) {
if (script[i].src === url) {
script = script[i];
if (!script.readyState && !script.onload) {
callback();
} else { // script not loaded so wait up to 10 seconds
var secs = 0, thisInterval = setInterval(function() {
secs++;
if (!script.readyState && !script.onload) {
clearInterval(thisInterval);
callback();
} else if (secs == 10) {
clearInterval(thisInterval);
console.log('could not load ' + url);
}
}, 1000);
}
return;
}
}
script = document.createElement('script');
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
if (script.readyState) {
script.onreadystatechange = function() {
if (script.readyState === 'loaded' || script.readyState === 'complete') {
script.onreadystatechange = null;
callback();
}
}
} else {
script.onload = function() {
script.onload = null;
callback();
}
}
script.src = url;
}
I my use case I'm leveraging heic2any to prepare images for upload. If the image is heic I convert it to png (blob), then pass the result to another utility (image blob reduce) to resize and sharpen before converting to jpg in preparation for upload. However, for the sake of simplicity the example below uses heic2any to convert to jpg in 1 step before upload.
function convertHEIC(file) {
return new Promise(function(resolve) {
if (!isHEIC(file)) return resolve(file);
loadScript('https://cdn.jsdelivr.net/npm/heic2any#0.0.3/dist/heic2any.min.js', function() {
heic2any({
blob: file,
toType: "image/jpg"
}).then(function (convertedFile) {
convertedFile.name = file.name.substring(0, file.name.lastIndexOf('.')) + '.jpeg';
resolve(convertedFile);
});
});
});
}
// convert any heic (and do any other prep) before uploading the file
convertHEIC(file).then(function(file) {
// code to upload (or do something else with file)
.
.
.
}

Convert _body content (string) to an arrayBuffer

I have an Ionic application which downloads a file from a Web API. The content of the file can be found in the _body property of the HTTP response.
What I'm trying to do is convert this text into an arrayBuffer so I can save the content into a file.
However, the issue that I'm having is that any file (PDF files in my instance) that have images and/or large in size either don't show up at all or show up as correputed files.
At first I thought this was an issue relating Ionic. So to make sure I tried to simulate this issue and I was able to reproduce it.
Is this snippet you can select a PDF file, then download it. You would find that the downloaded file is corrupted and exactly how my Ionic app displays them.
HTML:
<input type="file" id="file_input" class="foo" />
<div id="output_field" class="foo"></div>
JS:
$(document).ready(function(){
$('#file_input').on('change', function(e){
readFile(this.files[0], function(e) {
//manipulate with result...
$('#output_field').text(e.target.result);
try {
var file = new Blob([e.target.result], { type: 'application/pdf;base64' });
var fileURL = window.URL.createObjectURL(file);
var seconds = new Date().getTime() / 1000;
var fileName = "cert" + parseInt(seconds) + ".pdf";
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
a.href = fileURL;
a.download = fileName;
a.click();
}
catch (err){
$('#output_field').text(err);
}
});
});
});
function readFile(file, callback){
var reader = new FileReader();
reader.onload = callback
//reader.readAsArrayBuffer(file);
reader.readAsText(file);
}
https://jsfiddle.net/68qeau3h/3/
Now, when using reader.readAsArrayBuffer(file); everything works as expected, however in my particular case, I used reader.readAsText(file); because this is how the data is retrieve for me, this is text form.
When adding these lines of code to try to convert the string into an arrayBuffer
...
var buf = new ArrayBuffer(e.target.result.length * 2); // 2 bytes for each char
var bufView = new Uint16Array(buf);
for (var i=0, strLen=e.target.result.length; i<strLen; i++) {
bufView[i] = e.target.result.charCodeAt(i);
}
var file = new Blob([buf], { type: 'application/pdf' });
...
This will not work and generate PDF files that the browser can't open.
So to recap, what I'm trying to do is somehow convert the result I get from reader.readAsText(file); to what reader.readAsArrayBuffer(file); produces. Because the files I'm working with, or the data im retrieving from my backend is this text form.

plupload dynamic multipart_params for in progress uploads lost on re-initialization

I have a view in which I initialize a pluploader. I am able to leave this view and still allow the uploads to complete. The problem I am having is that whenever I re-enter the view, and there are uploads that are still in progress, the last multipart_param for "processId" that was assigned within "BeforeUpload" is used repeatedly instead of individually for each file.
Here's an example:
I drop 5 files on the view. I leave the view. Meanwhile 2 files have completed upload progress. The processId for file 1 was "0123" and the processId for file 2 was "0124". I then re-enter the view. This script is ran again. The remaining files are all assigned processId 0124.
I'm sure this is happening because the script is being ran any time you enter the view and something is being overwritten, but I've yet to find a solution.
You can see within the uploader.fileAdded area, that I create a random series of int called a processId with this line
var processId = process.createProcessId(file.index);
Then below, within BeforeUpload, I assign that processId to a multipart_param so that I can assign a unique processId to each upload.
uploader.settings.multipart_params.processId = file.processId;
The Script
/* detects when a user drags files from the desktop */
initDragDetector:function(){
var runtimes = ui.getUploadRunTimes();
var tmpId = Math.random();
uploader = new plupload.Uploader({
runtimes :runtimes,
max_file_size :'500mb',
url :jQuery('#upSrvUrl').val(),
drop_element :'uploadOverlay',
browse_button :'uploadOverlay',
filters : [
{title : "Image files", extensions : "jpg,tif,png,psd"},
],
max_file_count :100,
multipart_params :{rnd_id:Math.random(),tmp_sid:tmpId},
multi_selection :true,
file_data_name :'upfile_0',
});
//INITIALIZATION HANDLER 1
uploader.bind('Init',function(up, params){
uploader.settings.multipart_params.mount = jQuery('#mount').val();
uploader.settings.multipart_params.publisherId = jQuery('#publisherId').val();
uploader.settings.multipart_params.upload_range = 100;
if(uploader.features.dragdrop){
var el = jQuery("#uploadOverlay");
el[0].ondragover = function(event) {
event.dataTransfer.dropEffect = "copy";
};
el[0].ondragenter = function(e) {
if(e.dataTransfer.types.length < 4){
el.show();
}
};
el[0].ondrop = function() {
if(jQuery('.photoThumbContainer').length > 0){
el.hide();
}
};
}
});
//FILES ADDED HANDLER 2 (called after a drop of files)
uploader.bind('FilesAdded', function(up, files){
var i = 0;
plupload.each(files, function(file) {
file.index = i;
uploader.fileAdded(file);
i++;
});
uploader.start();
});
//inject the file into the interface (before before upload function)
uploader.fileAdded = function(file){
var processId = process.createProcessId(file.index);
//added to the file object and passed into the registration
file.processId = processId;
};
//BEFORE EACH UPLOAD HANDLER 3
//Note: this has to be here for any variable passed that changes per file. For example the processId.
uploader.bind('BeforeUpload',function(up,file){
var processId = file.processId;
var photoDiv = jQuery('#photo'+processId+' .photoThumbDiv');
var image = jQuery(new Image()).appendTo(photoDiv);
var preloader = new mOxie.Image();
preloader.downsize(100,100);
preloader.onload = function() {
var img = preloader.getAsDataURL();
jQuery('#photo'+processId+' .photoThumbDiv').html('<img src="'+img+'">');
};
preloader.load(file.getSource());
uploader.settings.multipart_params.processId = file.processId;
});
//PROGRESS HANDLER 4
uploader.bind('UploadProgress',function(up,file){
var processId = file.processId;
var pb = collection.getProgressBar(processId);
if(file.percent<100){
var progress = file.percent;
pb.html('<div class="progressBar"><div class="progressBarColor"> </div></div>');
jQuery('#photo'+processId+' .progressBarColor').css({width:progress+'%'});
}else{
pb.html('<div class="loaderSmall"></div> Processing');
}
});
//FILE FINISHED HANDLER 5
uploader.bind('FileUploaded',function(up,file,info){
var processId = file.processId;
var fileName = file.name;
file.fileName = file.name;
var params = file;
delete params.getNative;
delete params.getSource;
delete params.destroy;
ui.request('registerFile','Photo',params);
//ALL COMPLETE
if(uploadedCnt == up.files.length){
//uploader.splice();
uploader.refresh();
}
});
//GENERAL ERROR HANDLER -
uploader.bind('Error', function(up, err) {
switch(err.code){
case plupload.FILE_EXTENSION_ERROR:
fileExtensions = '';
jQuery.each(up.settings.filters.mime_types,function(index,up) {
if(fileExtensions==''){
fileExtensions=up.extensions;
}else{
fileExtensions+=","+up.extensions;
}
});
var isOrAre = (fileExtensions && fileExtensions.indexOf(',') !== -1) ? 'are':'is';
alertBox.msg("Only "+fileExtensions+" "+isOrAre+" accepted. Please try again.");
break;
case plupload.FILE_SIZE_ERROR:
alertBox.msg("File size can not be larger than "+up.settings.max_file_size+'.');
break;
}
uploader.refresh();
});
uploader.init();
},
Any input is appreciated. Thanks.
If anyone is interested in the solution here, it is because uploader was being set globally. Adding 'var' in front of uploading whenever initializing the uploader fixed it.

Using CKEditor custom filebrowser and upload with ASP.Net MVC

I have a MVC app that Im trying to use CKEditor with. One example I was looking at is here but there are many others. So far so good, but one section im still curious about, is the js that sends the selected file name back to the file upload dialog textbox.
<script type="text/javascript">
$(document).ready(function () {
$(".returnImage").click("click", function (e) {
var urlImage = $(this).attr("data-url");
window.opener.updateValue("cke_72_textInput", urlImage);
window.close();
});
});
</script>
In particular, the cke_72_textInput element. My example wasnt working initially, until I opened chrome dev tools and found the actual id of the textinput, which was in my case cke_76_textInput. Why the id change I wonder? Seems a little "fragile" to refer to a specific id like this? The above js code just takes the selected image file and returns it into the textbox of the fileupload dialog.
Is there something exposed that references this textbox element indirectly without specifying it by id (via the config for example)?
On view:
$(document).ready(function () {
CKEDITOR.replace('Text-area-name', {
filebrowserImageUploadUrl: '/Controller-name/UploadImage'
});
CKEDITOR.editorConfig = function (config) {
// Define changes to default configuration here. For example:
config.language = 'de';
// config.extraPlugins = 'my_own_plugin'; // if you have any plugin
// config.uiColor = '#AADC6E';
// config.image_previewText = CKEDITOR.tools.repeat(' Hier steht dann dein guter Text. ', 8 );
// config.contentsLanguage = 'de';
config.height = 350; // 350px, specify if you want a larger height of the editor
config.linkShowAdvancedTab = false;
config.linkShowTargetTab = false;
};
CKEDITOR.on('dialogDefinition', function (ev) {
var dialogName = ev.data.name;
var dialogDefinition = ev.data.definition;
ev.data.definition.resizable = CKEDITOR.DIALOG_RESIZE_NONE;
if (dialogName == 'link') {
var infoTab = dialogDefinition.getContents('info');
infoTab.remove('protocol');
dialogDefinition.removeContents('target');
dialogDefinition.removeContents('advanced');
}
if (dialogName == 'image') {
dialogDefinition.removeContents('Link');
dialogDefinition.removeContents('advanced');
var infoTab = dialogDefinition.getContents('info');
infoTab.remove('txtBorder');
infoTab.remove('txtHSpace');
infoTab.remove('txtVSpace');
infoTab.remove('cmbAlign');
}
});
}
On Contoller:
[HttpPost]
public ActionResult UploadImage(HttpPostedFileBase file, string CKEditorFuncNum, string CKEditor, string langCode)
{
if (file.ContentLength <= 0)
return null;
// here logic to upload image
// and get file path of the image
const string uploadFolder = "Assets/img/";
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath(string.Format("~/{0}", uploadFolder)), fileName);
file.SaveAs(path);
var url = string.Format("{0}{1}/{2}/{3}", Request.Url.GetLeftPart(UriPartial.Authority),
Request.ApplicationPath == "/" ? string.Empty : Request.ApplicationPath,
uploadFolder, fileName);
// passing message success/failure
const string message = "Image was saved correctly";
// since it is an ajax request it requires this string
var output = string.Format(
"<html><body><script>window.parent.CKEDITOR.tools.callFunction({0}, \"{1}\", \"{2}\");</script></body></html>",
CKEditorFuncNum, url, message);
return Content(output);
}
I had the same problem...a little frustrating that I couldn't find any official documentation, considering this seems like a common use case.
Anyways, take a look at the quick tutorial here: http://r2d2.cc/2010/11/03/file-and-image-upload-with-asp-net-mvc2-with-ckeditor-wysiwyg-rich-text-editor/. In case the link ever breaks, here's what I did.
[HttpPost]
public ActionResult UploadImage(HttpPostedFileBase upload, string ckEditorFuncNum)
{
/*
add logic to upload and save image here
*/
var path = "~/Path/To/image.jpg"; // Logical relative path to uploaded image
var url = string.Format("{0}://{1}{2}",
Request.Url.Scheme,
Request.Url.Authority,
Url.Content(path)); // URL path to uploaded image
var message = "Saved!"; // Optional
var output = string.Format("<script>window.parent.CKEDITOR.tools.callFunction({0}, '{1}', '{2}');</script>",
CKEditorFuncNum,
url,
message);
return Content(output);
}

How to upload base64 image resource with dropzone?

I'm trying to upload generated client side documents (images for the moment) with Dropzone.js.
// .../init.js
var myDropzone = new Dropzone("form.dropzone", {
autoProcessQueue: true
});
Once the client have finished his job, he just have to click a save button which call the save function :
// .../save.js
function save(myDocument) {
var file = {
name: 'Test',
src: myDocument,
};
console.log(myDocument);
myDropzone.addFile(file);
}
The console.log() correctly return me the content of my document
data:image/png;base64,iVBORw0KGgoAAAANS...
At this point, we can see the progress bar uploading the document in the drop zone but the upload failed.
Here is my (standart dropzone) HTML form :
<form action="/upload" enctype="multipart/form-data" method="post" class="dropzone">
<div class="dz-default dz-message"><span>Drop files here to upload</span></div>
<div class="fallback">
<input name="file" type="file" />
</div>
</form>
I got a Symfony2 controller who receive the post request.
// Get request
$request = $this->get('request');
// Get files
$files = $request->files;
// Upload
$do = $service->upload($files);
Uploading from the dropzone (by drag and drop or click) is working and the uploads are successfull but using the myDropzone.addFile() function return me an empty object in my controller :
var_dump($files);
return
object(Symfony\Component\HttpFoundation\FileBag)#11 (1) {
["parameters":protected]=>
array(0) {
}
}
I think i don't setup correctly my var file in the save function.
I tryied to create JS image (var img = new Image() ...) but without any success.
Thanks for your help !
Finally i found a working solution without creating canvas :
function dataURItoBlob(dataURI) {
'use strict'
var byteString,
mimestring
if(dataURI.split(',')[0].indexOf('base64') !== -1 ) {
byteString = atob(dataURI.split(',')[1])
} else {
byteString = decodeURI(dataURI.split(',')[1])
}
mimestring = dataURI.split(',')[0].split(':')[1].split(';')[0]
var content = new Array();
for (var i = 0; i < byteString.length; i++) {
content[i] = byteString.charCodeAt(i)
}
return new Blob([new Uint8Array(content)], {type: mimestring});
}
And the save function :
function save(dataURI) {
var blob = dataURItoBlob(dataURI);
myDropzone.addFile(blob);
}
The file appears correctly in dropzone and is successfully uploaded.
I still have to work on the filename (my document is named "blob").
The dataURItoBlob function have been found here : Convert Data URI to File then append to FormData
[EDIT] : I finally wrote the function in dropzone to do this job. You can check it here : https://github.com/CasperArGh/dropzone
And you can use it like this :
var dataURI = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAmAAAAKwCAYAAA...';
myDropzone.addBlob(dataURI, 'test.png');
I can't comment currently and wanted to send this to you.
I know you found your answer, but I had some trouble using your Git code and reshaped it a little for my needs, but I am about 100% positive this will work for EVERY possible need to add a file or a blob or anything and be able to apply a name to it.
Dropzone.prototype.addFileName = function(file, name) {
file.name = name;
file.upload = {
progress: 0,
total: file.size,
bytesSent: 0
};
this.files.push(file);
file.status = Dropzone.ADDED;
this.emit("addedfile", file);
this._enqueueThumbnail(file);
return this.accept(file, (function(_this) {
return function(error) {
if (error) {
file.accepted = false;
_this._errorProcessing([file], error);
} else {
file.accepted = true;
if (_this.options.autoQueue) {
_this.enqueueFile(file);
}
}
return _this._updateMaxFilesReachedClass();
};
})(this));
};
If this is added to dropzone.js (I did just below the line with Dropzone.prototype.addFile = function(file) { potentially line 1110.
Works like a charm and used just the same as any other. myDropzone.addFileName(file,name)!
Hopefully someone finds this useful and doesn't need to recreate it!
1) You say that: "Once the client have finished his job, he just have to click a save button which call the save function:"
This implies that you set autoProcessQueue: false and intercept the button click, to execute the saveFile() function.
$("#submitButton").click(function(e) {
// let the event not bubble up
e.preventDefault();
e.stopPropagation();
// process the uploads
myDropzone.processQueue();
});
2) check form action
Check that your form action="/upload" is routed correctly to your SF controller & action.
3) Example Code
You may find a full example over at the official Wiki
4) Ok, thanks to your comments, i understood the question better:
"How can i save my base64 image resource with dropzone?"
You need to embedd the image content as value
// base64 data
var dataURL = canvas.toDataURL();
// insert the data into the form
document.getElementById('image').value = canvas.toDataURL('image/png');
//or jQ: $('#img').val(canvas.toDataURL("image/png"));
// trigger submit of the form
document.forms["form1"].submit();
You might run into trouble doing this and might need to set the "origin-clean" flag to "true". see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#security-with-canvas-elements
how to save html5 canvas to server

Categories

Resources