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 ?!
A File object is created by passing in a string that represents the name of a file, a String, or another File object. For example, File a = new File("/usr/local/bin/geeks"); This defines an abstract file name for the geeks file in the directory /usr/local/bin.
We can create a file with the File constructor with JavaScript. For instance, we can write: const parts = [ new Blob(['you construct a file...'], { type: 'text/plain' }), ' Same way as you do with blob', new Uint16Array([33]) ]; const file = new File(parts, 'sample.
With TypeScript installed, you can initialize your TypeScript project by using the following command: npx tsc --init.
A File object is a specific kind of Blob , and can be used in any context that a Blob can. In particular, FileReader , URL. createObjectURL() , createImageBitmap() , and XMLHttpRequest.
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);
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With