i am new to coffeescript. i have already written code in js, now i want to convert it in coffeescript,i have try a lot,i have refer This also. but it won't help me.
here is my code,
this.$scope.callTestFuntion = function(){
this.blockingObject.render(function(dataURL){
console.log('via render');
console.log(dataURL.length);
});
}
this.$scope.blockingObject.callback=function(dataURL){
console.log('via function');
console.log(dataURL.length);
this.myCroppedImage = dataURL;
}
var handleFileSelect=function(evt) {
console.log('here');
var file=evt.currentTarget.files[0];
var reader = new FileReader();
reader.onload = function (evt) {
this.$scope.$apply(function($scope){
this.$scope.myImage=evt.target.result;
});
};
reader.readAsDataURL(file);
};
I want to convert it in coffeescript syntax. please help me.
Thanks
If you just want to convert the code then use http://js2.coffee
#$scope.callTestFuntion = ->
#blockingObject.render (dataURL) ->
console.log 'via render'
console.log dataURL.length
return
return
#$scope.blockingObject.callback = (dataURL) ->
console.log 'via function'
console.log dataURL.length
#myCroppedImage = dataURL
return
handleFileSelect = (evt) ->
console.log 'here'
file = evt.currentTarget.files[0]
reader = new FileReader
reader.onload = (evt) ->
#$scope.$apply ($scope) ->
#$scope.myImage = evt.target.result
return
return
reader.readAsDataURL file
return
# ---
# generated by js2coffee 2.2.0
Here is your converted code:
# CoffeeScript code converted from JavaScript
# from Georgi Naumov
# gonaumov#gmail.com for contacts and suggestions
#.$scope.callTestFuntion = ->
#.blockingObject.render (dataURL) ->
console.log 'via render'
console.log dataURL.length
#.$scope.blockingObject.callback = (dataURL) ->
console.log 'via function'
console.log dataURL.length
#.myCroppedImage = dataURL
handleFileSelect = (evt) ->
console.log 'here'
file = evt.currentTarget.files[0]
reader = new FileReader()
reader.onload = (evt) ->
#.$scope.$apply ($scope) ->
#.$scope.myImage = evt.target.result
reader.readAsDataURL file
And here is resulted JavaScript after compilation:
// Generated by CoffeeScript 1.12.3
(function() {
var handleFileSelect;
this.$scope.callTestFuntion = function() {
return this.blockingObject.render(function(dataURL) {
console.log('via render');
return console.log(dataURL.length);
});
};
this.$scope.blockingObject.callback = function(dataURL) {
console.log('via function');
console.log(dataURL.length);
return this.myCroppedImage = dataURL;
};
handleFileSelect = function(evt) {
var file, reader;
console.log('here');
file = evt.currentTarget.files[0];
reader = new FileReader();
reader.onload = function(evt) {
return this.$scope.$apply(function($scope) {
return this.$scope.myImage = evt.target.result;
});
};
return reader.readAsDataURL(file);
};
}).call(this);
Related
I'm trying to pass the path from the function for get the binary file base64 String, as like below.
var file = 'dir/file.pdf';
function getBase64(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
console.log(reader.result);
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
But as it returning me undefined
i need similar like this
data:application/pdf;base64,JVBERi0xLjUKJdDUxdgKNSAws2...
How this can be done?
With fileReader you can convert your file from path like this :
var file = new File("/pdf/test.pdf","r");
function getBase64(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
console.log(reader.result);
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
The solution of Lèo is good, except that it is necessary to use the good arguments for the constructor's file. Example :
var file = new File(["foo"], "/pdf/test.pdf", {type: 'application/pdf'});
Here the documentation of the Api: File mdn
How to get string Base64 from an input file .pdf.
i have this function but i dont return the string base64.
the files extencion accept are .pdf
I NEED THE STRING BASE64 IN AN VARIABLE
My code:
<input type="file" id="files" name="files" multiple>
Js code
var base64 = getBase64(document.getElementById('files').files[0])
function getBase64(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
console.log(reader.result);
return(reader.result); //THIS NO RETURN NOTHING. WHY?
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
I tested it, it works, you have to add it on the change event, you are calling the getbase64 before anything is there:
https://jsfiddle.net/ibowankenobi/fcgL3dn8/
document.getElementsByTagName("input")[0].addEventListener("change",getBase64,false);
var _file;
function getBase64() {
var file = this.files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
console.log(reader.result);
_file = reader.result;
//don't do the below. It is pointless. Either assign the result to a variable within scope or call a callback
//return(reader.result); //THIS NO RETURN NOTHING. WHY?
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
I'm trying to write a service which reads the image file from an HTML input element. I want this service to return the HTML img object with the updated attribute from the read image file (the base64 string). My service is now this:
.service('ReadLocalImageService', [function () {
this.openLocalImage = function (file) {
var img = document.createElement("img");
var fileReader = new FileReader();
fileReader.onload = function (e) {
img.src = e.target.result;
};
fileReader.readAsDataURL(file);
return img.src;
};
}]);
The img.src in this case is returned empty, like this:
If I put a console.log(img.src) inside the fileReader.onload, it prints out what I want. It seems like the function openLocalImage is returning the img.src before e.target.result is assigned to it.
I couldn't manage to work this around nor find the correct topic about this problem. Could anyone help me solve this or explain me why it doesn't work?
Its because img was not loaded yet. Here is a solution
.service('ReadLocalImageService', [function () {
this.openLocalImage = function (file, callback) {
var img = document.createElement("img");
var fileReader = new FileReader();
fileReader.onload = function (e) {
img.src = e.target.result;
callback(img.src);
};
fileReader.readAsDataURL(file);
};
}]);
We will pass a callback function and receive img.src as its param. To use it
ReadLocalImageService.openLocalImage(myImage, function(imgSrc) {
// use imgSrc
});
This is the code I have for reading the first item in a file input, how can I iterate over all items inside this input?
function readFile (uploadControlId) {
if (!window.FileReader)
throw "The browser does not support HTML 5";
var element = document.getElementById(uploadControlId);
var def = new $.Deferred();
var file = element.files[0];
var parts = element.value.split("\\");
var fileName = parts[parts.length - 1];
var reader = new FileReader();
reader.onload = function (e) {
if (uploadControlId == 'uploadControlId'){
def.resolve(e.target.result, fileName);
} else {
def.resolve(e.target.result, fileName);
}
};
reader.onerror = function (e) {
def.reject(e.target.error);
};
reader.readAsArrayBuffer(file);
return def.promise();
}
I have tried something like:
angular.forEach(element.files, function (file){
})
But this doesn't work since the variables 'parts' and 'fileName' is from the variable 'element', so if I iterate over each file in element, they get 'undefined' fileName, this means they won't have like .txt or .pdf, so they are unreadable.
Update: This give no error, but only the last file gets uploaded:
function readFile (uploadControlId) {
if (!window.FileReader)
throw "The browser does not support HTML 5";
var def = new $.Deferred();
var element = document.getElementById(uploadControlId);
angular.forEach(element.files, function(file){
var fileName = file.name;
var reader = new FileReader();
reader.onload = function (e) {
def.resolve(e.target.result, fileName);
};
reader.onerror = function (e) {
def.reject(e.target.error);
};
reader.readAsArrayBuffer(file);
});
return def.promise();
}
My upload function:
$scope.UploadAttachment = function(){
readFile(uploadControlId).done(function (buffer, fileName) {
// logic to upload to server
}).fail(function (err) {
alert("error in reading file content");
});
};
Have you added the "multiple" attribute on the input tag?
By the way if you add this directive to your tag, an event will be fired with all files and you will handle that in you controller.
// Directive
(function(){
var Directive = function(){
return {
restrict: 'A',
scope : {},
link : function(scope, element, attrs){
element.bind('change', function(changeEvent){
scope.$emit('fileReader', changeEvent.target.files);
});
}
}
};
Directive.$inject = [];
app.directive('fileReader', Directive);
})();
// Controller
(function(){
var Controller = function($scope){
// Methods
function fileReader(files){
for(var iFile = 0, fileLen = files.length; iFile < fileLen; iFile = iFile + 1){
var file = files[iFile];
// Do something
}
}
// Events
$scope.$on('fileReader', function(event, files){
fileReader(files);
});
};
Controller.$inject = [
'$scope'
];
app.controller('MainCtrl', Controller);
})();
I have a list of files I need to save and in addition to the name I need to send the readAsDataURL to the server as well.
The problem is I am not sure how to do it with the async nature of readAsDataURL. Because to save the DATAURL to the array I need to look up the name of the file which is in the files list. and I cannot pass the file to the async method of readAsDataURL. How do you write this properly to work? The end result is I want a list of files sent to the server in one JSZip file.
function saveFileList(files)
{
for (var i = 0, file; file = files[i]; i++) {
var fr = new FileReader();
fr.onload = function(e){
if (e.target.readyState == FileReader.DONE) {
var tt = e.target.result.split(",")[1];
//update the record in the list with the result
}
};
var pp = fr.readAsDataURL(file);
}
If you have FileList and you need to get array of base64 string, you need do this
export async function fileListToBase64(fileList) {
// create function which return resolved promise
// with data:base64 string
function getBase64(file) {
const reader = new FileReader()
return new Promise(resolve => {
reader.onload = ev => {
resolve(ev.target.result)
}
reader.readAsDataURL(file)
})
}
// here will be array of promisified functions
const promises = []
// loop through fileList with for loop
for (let i = 0; i < fileList.length; i++) {
promises.push(getBase64(fileList[i]))
}
// array with base64 strings
return await Promise.all(promises)
}
use it like this
const arrayOfBase64 = await fileListToBase64(yourFileList)
You need another function around it, so you can pass the file in. Try this:
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
if(reader.readyState == FileReader.DONE)
alert(theFile.name); // The file that was passed in.
}
};
})(file);
reader.readAsDataURL(file);
An alternative to Russell G's answer:
var reader = new FileReader();
reader.onload = function(event){
payload = event.target.result;
var filename = file.name, filetype = file.type;//etc
//trigger a custom event or execute a callback here to send your data to server.
};
reader.onerror = function(event){
//handle any error in here.
};
reader.readAsDataURL(file);