/    Sign up×
Community /Pin to ProfileBookmark

Problem with File API

I am using the File API to read a file in javascript. Is there a way to do this without creating an event with “reader.onload = function(e)”?
I want it work in the code below. As it is now the variable fileContent doesn’t contain anything when I try to read it.
I understand why the code below doesn’t work like that but is there any other way to make it work like that?
Do someone understand what I am trying to achieve?

[CODE]var fileContent;

function myFunction()
{
readFile();

processData();
}

function readFile()
{
file = myFiles[0];

var reader = new FileReader();

reader.onload = function(e)
{
fileContent = e.target.result;
}

reader.readAsText(file);
}

function processData()
{
alert(fileContent);
}[/CODE]

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@rnd_meFeb 24.2012 — are you sure it doesn't work, or are you looking at [I]fileContent [/I]before it's set?
[CODE] reader.onload = function(e)
{
fileContent = e.target.result;
alert(fileContent);
}[/CODE]
Copy linkTweet thisAlerts:
@larskauthorFeb 25.2012 — are you sure it doesn't work, or are you looking at [I]fileContent [/I]before it's set?
[CODE] reader.onload = function(e)
{
fileContent = e.target.result;
alert(fileContent);
}[/CODE]
[/QUOTE]


Thanks for your answer. I know that it isn't set yet but I want to use it under the function processData. Is there a way to read a file without an event?
Copy linkTweet thisAlerts:
@hyperionXSFeb 25.2012 — No, you can't. But you can try this:
[CODE]
var fileContent;

function myFunction()
{
readFile();
}

function readFile()
{
file = myFiles[0];

var reader = new FileReader();

reader.onload = function(e)
{
fileContent = e.target.result;

processData();
}

reader.readAsText(file);
}

function processData()
{
alert(fileContent);
}
[/CODE]
×

Success!

Help @larsk spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.11,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...