18

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 ?!

Danilo Valente
  • 10,599
  • 8
  • 49
  • 65
Yahia
  • 572
  • 1
  • 5
  • 24
  • 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. :) – Juho Vepsäläinen May 09 '11 at 07:02
  • developing mobile app using html5 , trying to save some data to SDCard and retrieve it again – Yahia May 09 '11 at 07:04
  • I think it might be easier for you to rely on localStorage. See http://dev.w3.org/html5/webstorage/ . – Juho Vepsäläinen May 09 '11 at 08:00
  • my stored data is being very big with time , i want to save it on SD – Yahia May 10 '11 at 03:04

2 Answers2

34

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);
}); 
Ashish
  • 7,621
  • 11
  • 48
  • 89
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.

James Williams
  • 4,163
  • 1
  • 17
  • 34