Filename change after using "canvas.toblob()!" - javascript

I am using Cropper.js to send a cropped image to a server, but when I use "convtoblob(blob )" and append blob to formfile then send it to web API, original image Filename miss and according to attached image change to "blob"!
Please help me!
Part of my code is shown below:
canvas.toBlob(function(blobs) {
//blobs.nam = FN;
var formData = new FormData();
formData.append("up", blobs);
$.ajax('http://localhost:51320/api/fileupload/uploadfile', {
method: 'POST',
processData: false,
contentType: false,
data: formData,
cache: false,
success: function(d) {
var d;
$alert.show().addClass('alert-success').text('Upload success');
},
error: function(d) {
var d;
avatar.src = initialAvatarURL;
$alert.show().addClass('alert-warning').text('Upload error');
},
complete: function(d) {
var d;
$progress.hide();
}
});
});
Even when I add a new property as you see "//blobs.nam = FN;" I don't get it in webAPI.
also i have got canvas-toBlob.js but any changes!
please help me!
web api print screen
html page print screen

You can append the formdata like this
formData.append('up', blobs, "blobs.jpg");
Third parameter is your file name.if you want to get your old file name please just read your input type="file" value like this
var yourFileName = $("#ImageFile").val().split('\\').pop(); and change the appending code to
formData.append('up', blobs, yourFileName );
it's tested and working fine.

Related

Saving images uploaded using ImagesLoader

I am trying to wire up the ImagesLoader plugin, which allows uploading multiple images. It has a nice drag-n-drop UI but I just can't figure out how to get the images that were uploaded. I cannot find any documentation.
Link to the plugin page: ImagesLoader
Here is the javascript from the demo:
<script type="text/javascript">
// Ready
$(document).ready(function () {
// Create image loader plugin
var imagesloader = $('[data-type=imagesloader]').imagesloader({
minSelect: 3
,imagesToLoad: [{"Url":"./img/Nespresso001.jpg","Name":"Nespresso001"},{"Url":"./img/Nespresso002.jpg","Name":"Nespresso002"}]
});
//Form
$frm = $('#frm');
// Form submit
$frm.submit(function (e) {
var $form = $(this);
var files = imagesloader.data('format.imagesloader').AttachmentArray;
var il = imagesloader.data('format.imagesloader');
if (il.CheckValidity())
alert('Upload ' + files.length + ' files');
e.preventDefault();
e.stopPropagation();
});
});
The images are saved in the object "files". Here is a screen shot of the contents from the inspector:
I tried converting to json and posting, but that only generates an error.
$.ajax({
url: 'process-images.php',
type: 'POST',
data: JSON.stringify(files),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
cache: false,
error: function() {alert("ERROR");},
success: function() {alert("OK");}
});
The rest of the code works just like the demo. Looks like everything needed for the uploaded images is stored in "files". I just need to get the data back to php and I can pull it apart from there. But right now, the original submit code just dies or my addition aborts with an error.
THANKS!
I hope it is not too late to answer.
You just need to loop through the base64 encoded image object, decoding and saving each image to the disk.
// Sample code
foreach(json_decode($request->input('files')) as $file) {
$name = $file->FileName
$imagePath = storage_path('app/public/images/');
file_put_contents($imagePath.$name, base64_decode($file->Base64));
}

uploading spreadsheet to parse.com from javascript

I am able to upload a spreadsheet (.csv or XLS files), but when checking on the file from Parse.com, it is all empty. I am uploading the file from client side code (not using REST). Do you think that is the problem? This works just fine for a simple image/file upload using a similar code, but fails for csv or xls type file.
Here's the code:
$scope.uploadSpFile = function(fileUpload){
var name = fileUpload.name;
var parseFile = new Parse.File(name, fileUpload.spFile);
var serverUrl = 'https://api.parse.com/1/files/' + fileUpload.name;
var mySpreadsheet = new Parse.Object(fileUpload.className);
$.ajax({
type: "POST",
beforeSend: function(request) {
request.setRequestHeader("X-Parse-Application-Id", parse_app_id);
request.setRequestHeader("X-Parse-REST-API-Key", parse_rest_id);
request.setRequestHeader("Content-Type", fileUpload.spFile.type);
},
url: serverUrl,
data: fileUpload.mySpreadsheet,
processData: false,
contentType: false,
success: function(data) {
mySpreadsheet.set({filetitle: data.name});
mySpreadsheet.set({fileurl: data.url});
mySpreadsheet.set({name: name});
mySpreadsheet.set({fileCategory: ''});
mySpreadsheet.set({file: {"name": data.name,"url": data.url,"__type": "File"}});
mySpreadsheet.save();
console.log('file saved!');
},
error: function(data) {
var obj = jQuery.parseJSON(data);
console.log('error: ' + obj.error);
outputMsg = obj.error;
}
});
}
});
when i use a similar code to upload an image, I can access the file on my parse page, but xls or csv files turn out to be empty (actually, in XLS case, an error pops out as the format is corrupted).
Anyone has any idea how to fix this issue?
thanks for the help.

Read local file text (tab separated values) with d3 or ajax cause syntax error in firefox development console

The reading works.
However I got a syntax error in the firefox console (which is tiresome when I read 30 files).
The files are annotation files like (time \t value) with no headers like :
0.0 5.2
0.5 5.6
1.0 6.3
...
This is the ajax code :
function getdatafromfile(filename) {
// Read annotation file. Example : %timeinstant \t %value \n
// Return an array of string
var arraydata
$.ajax({
type: "GET",
url: filename,
dataType: "text",
async: false,
success: function(csv) {arraydata = $.csv.toArrays(csv,{separator:'\t'}); }
});
return arraydata}
And with d3:
d3.text(filename, function(text) {
var data = d3.tsv.parseRows(text).map(function(row) {
return row.map(function(value) {
return +value;
});
});
console.log(data);
});
}
It seems that I could use one of those code, but I got a syntax error in both cases (with firefox 33.1).
A file reader could work like the code below.
In the example I've added a flag to use the content of the variable instead of a file. That's just for the demo and can be removed. The same code is here as jsFiddle.
Maybe you could add some validation before or after the $.csv method. So you know that the file was a csv/tsv file.
If you need to open the file with-out user interaction, you have to look for something different because JS is not allowed to open a file with-out the user choosing the file (security concerns, see this SO question).
You could add your data to a database and read it from there. e.g. Firebase or MongoDB or use a JSON file. The code of my other answer should work for a JSON file that you host with your webpage.
var demoTxt = "0.0 5.2\
0.5 5.6\
1.0 6.3";
var flag_usedemofile = true; //if true var demoTxt will be used
function doOpen(evt) {
var files = evt.target.files,
reader = new FileReader();
reader.onload = function() {
if ( !flag_usedemofile) {
var arraydata = $.csv.toArrays(this.result,{separator:' '});
showout.value = arraydata; //this.result;
} else {
var arraydata = $.csv.toArrays(demoTxt,{separator:' '});
showout.value = arraydata;
console.log(arraydata);
}
};
reader.readAsText(files[0]);
}
var openbtn = document.getElementById("openselect"),
showout = document.getElementById("showresult");
openselect.addEventListener("change", doOpen, false);
#showresult {
width:98%;
height: 300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script>
<input type="file" id="openselect" />
<textarea id="showresult"></textarea>
I'm not exactly sure what syntax error you are getting. But I think the error have something to do with the mime type of your json request.
I think the best way is to wrap your data in json and then use JSONP. (I have also tried to get it working with text/plain, but with-out success.)
Please check the following example for details. You can also find the same example on
jsFiddle.
(function ($) {
var url = 'http://www.mocky.io/v2/547c5e31501c337b019a63b0'; // dummy url
var jsonCallback = function (csv) {
var arraydata;
console.log(data);
$('#data').html(JSON.stringify(csv, null, 2));
arraydata = $.csv.toArrays(csv.data,{separator:'\t'});
console.log(arraydata);
};
$.ajax({
type: 'GET',
url: url,
contentType: "application/json",
dataType: 'jsonp'
}).done(jsonCallback)
.fail(function (xhr) {
alert("error" + xhr.responseText);
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id='data'></pre>

Uploaded file only contains "WebKitFormBoundary"

I don't really know what's going on here. Every time I try to upload a file, all the file contains is:
------WebKitFormBoundaryJ0uWMNv89fcUsC1t--
I have searched for the past 2 days for some sort of explanation, but I am just going in circles. I have no idea why this is happening.
Form:
<form id="upload-file" ecntype="multipart/form-data">
<input name="picture" type="file">
<input type="button" value="Upload" id="upload-button" />
</form>
Javascript:
$('#upload-button').click(function(e){
e.preventDefault();
var formData = new FormData($('#upload-file'));
$.ajax({
url: '/image',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.addEventListener('progress',progressHandlingFunction, false);
}
return myXhr;
},
data: formData,
cache: false,
// contentType: false,
processData: false
});
});
Controller:
def image = Action(parse.temporaryFile) { request =>
request.body.moveTo(new File("/tmp/picture"))
Ok("File uploaded")
}
The problem was occuring in the Javascript, not the Scala. I was not referencing the form elements improperly.
var formData = new FormData($('#upload-file')[0]);
However, I also had problems with parse.temporaryFile and it was not properly storing the file using the code above. When I inspected the stored files in a text editor, I noticed it still had the ------WebKitFormBoundaryJ0uWMNv89fcUsC1t-- stuff at the beginning of the file, followed by the form information, then followed by the file bytes.
To fix this, I just used the default method for multipartform upload as per the Play Documentation, and it worked perfectly.
def image = Action(parse.multipartFormData) { request =>
request.body.file("picture").map { picture =>
val filename = picture.filename
picture.ref.moveTo(new File(s"/tmp/picture/$filename"))
Ok("ok")
}.getOrElse {
InternalServerError("file upload error")
}
}

Can't save image via HTML canvas

I'm having difficulties saving my canvas. I'm new to javascript so I think it could be a syntax issue.
I've got some vars saved in a function:
var imageView = document.getElementById("imageView");
var canvasData = imageView.toDataURL("image/png");
var postData = "canvasData="+canvasData;
If I add the following line it displays the image correctly:
imgData = $('#i').append($('<img/>', { src : canvasData }));
However, I have another function that I want to pass the base64 code in so I added:
var the_data = "test= "+imageView.toDataURL("image/png");
It does print out a base64 code, but just the blank canvas (not with the drawing the user has added).
If I add the following it doesn't work:
var the_data = "test= "+canvasData;
What am I doing wrong?
This is a basic jsfiddle of what I'm trying to do: http://jsfiddle.net/sMSeX/
Just a little hint from my side for uploading HTML5 canvas image data:
I am working on a project for a print-shop and had some problems due to uploading images to the server that came from an HTML5 canvas element. I was struggling at least for one hour and I did not get it to save the image correctly on my server.
I get the image data as Base64 decoded from the canvas element via
var can = document.getElementsByTagName('canvas');
var dataURL = can[0].toDataURL("image/jpg");
//dataURL = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
console.log('data url: '+dataURL);
Once I set the
contentType option of my jQuery ajax call to 'application/x-www-form-url-encoded' :
$.ajax({
url: 'index.php?page=upload-image',
type: 'post',
contentType: 'application/x-www-form-urlencoded',
//data: '{ "imageData" : "' + dataURL + '" }',
data: dataURL,
beforeSend: function() {
$('.text-danger').remove();
},
complete: function() {
},
success: function(json) {
console.log('upload complete');
}
});
everything went the right way and the base64-encoded data was interpreted correctly and successfully saved as an image.
Maybe someone helps that!

Categories