20

there is many examples of reading local files using html5 but by choosing from list of files , my problem is that i want to create the file object manually , think about i have a file with the link

file:///G:/Users/txt.txt

i want the browser to open it ,

i think it have to File f=new File('file:///G:/Users/txt.txt');

my question is how to create/initialize the file object using file path ?!

4
  • 1
    I would not be surprised if this was not possible due to file system differences (UNIX vs. Win convention etc.) and security. I certainly would not want my browser to override some file of mine without me knowing about it. :) Commented May 9, 2011 at 7:02
  • developing mobile app using html5 , trying to save some data to SDCard and retrieve it again Commented May 9, 2011 at 7:04
  • I think it might be easier for you to rely on localStorage. See dev.w3.org/html5/webstorage . Commented May 9, 2011 at 8:00
  • my stored data is being very big with time , i want to save it on SD Commented May 10, 2011 at 3:04

2 Answers 2

37

I have used below workaround since File inherits blob interface.

var getFileBlob = function (url, cb) {
        var xhr = new XMLHttpRequest();
        xhr.open("GET", url);
        xhr.responseType = "blob";
        xhr.addEventListener('load', function() {
            cb(xhr.response);
        });
        xhr.send();
};

var blobToFile = function (blob, name) {
        blob.lastModifiedDate = new Date();
        blob.name = name;
        return blob;
};

var getFileObject = function(filePathOrUrl, cb) {
       getFileBlob(filePathOrUrl, function (blob) {
          cb(blobToFile(blob, 'test.jpg'));
       });
};

getFileObject('img/test.jpg', function (fileObject) {
     console.log(fileObject);
}); 
Sign up to request clarification or add additional context in comments.

2 Comments

I have to use XMLHttpRequest even for a local file path?
Does this work on android too, works well on iOS but android seems to not like it....?
2

There really is no way to create a file without permission from the user. A button or something will need to be pressed. You would need to create a data:uri in order for it to save. You can find more information using a web search or checking out http://en.wikipedia.org/wiki/Data_URI_scheme (not a complete source but can show what is possible). This is very limited depending on phone and OS. Data URI are limited while using IE.

When it is triggered for download, it saves to t he default location or user specified. You may also want to look into vendor/OS specific API Calls that can do as you are describing. But may need to verify permissions prior to actually allowing access.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.