Javascript 如何使用文件路径html5创建/初始化文件对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5933565/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to create/initialize the file object using file path html5
提问by Yahia
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
有很多使用 html5 读取本地文件的例子,但是通过从文件列表中选择,我的问题是我想手动创建文件对象,想想我有一个带有链接的文件
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');
我认为它必须归档 f=new File('file:///G:/Users/txt.txt');
my question is how to create/initialize the file object using file path ?!
我的问题是如何使用文件路径创建/初始化文件对象?!
采纳答案by James Williams
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.
没有用户的许可,真的没有办法创建文件。需要按下按钮或其他东西。您需要创建一个 data:uri 才能保存它。您可以使用网络搜索或查看http://en.wikipedia.org/wiki/Data_URI_scheme(不是完整的来源,但可以展示可能的内容)找到更多信息。这非常有限,具体取决于手机和操作系统。使用 IE 时数据 URI 受到限制。
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.
当它被触发下载时,它保存到默认位置或用户指定。您可能还想查看可以按照您的描述执行的特定于供应商/操作系统的 API 调用。但可能需要在实际允许访问之前验证权限。
回答by Ashish
I have used below workaround since File inherits blob interface.
由于 File 继承了 blob 接口,因此我使用了以下解决方法。
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);
});