Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I want to convert a html input file to a json string like this:

var jsonString = JSON.stringify(file);
console.log( file );
console.log( jsonString );

Now, in my firebug:

File { size=360195, type="image/jpeg", name="xyz.jpg", mehr...} 
Object {}

Why is the jsonString empty?

Background info: I want to send the file-reference with jsonp to another php server

Additional Information: I want to convert only the file-pointer (reference) to a string, to send it via GET.

share|improve this question

migrated from programmers.stackexchange.com Jun 10 at 10:54

This question came from our site for professional programmers interested in conceptual questions about software development.

add comment

1 Answer

You have to read the file content using the FileReader API. The File object does not contain the file content (it is just a pointer toward the file, which allows you to read it later).

You can check out this HTML5Rocks article to find out more about the usage of this API.

var file = getAFile( );

var success = function ( content ) {
  console.log( JSON.stringify( content ) ); }

var fileReader = new FileReader( );
fileReader.onload = function ( evt ) { success( evt.target.result ) };
fileReader.readAsText( file );
share|improve this answer
    
Thank you for your answer. I want to send the pointer to another server. So I have to convert the file-pointer to a string. Do you have an idea? –  peacemaker Jun 10 at 13:44
    
Did you read the article ? evt.target.result is a string containing the file content. Using the FileReader API is the only way to fetch it, for security reasons. –  Maël Nison Jun 11 at 14:08
    
I think this is not the solution in my project. There is a problem because I will send the string with GET. The size of the string is too long if the file is for example 500 MB. –  peacemaker Jun 12 at 7:44
    
Well, then don't send it using GET? I'm not sure to understand what you want. If you just need to post a file, do it with FormData rather than JSON, since the former can streamline a file upload without requiring to buffer its content in the RAM. –  Maël Nison Jun 13 at 9:12
    
I want to send the file(-pointer) to another server...so I have to use GET... –  peacemaker Jun 13 at 14:08
show 1 more comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.