【发布时间】:2016-09-17 16:31:44
【问题描述】:
我顺便使用了 react,但事实仍然存在:当我建立一个带有输入的简单页面来上传本地文件时,如果我 console.log 选择了实际文件,这就是我从控制台:
File {name: "myfile.mp4", lastModified: 1474084788000, lastModifiedDate: Fri Sep 16 2016 23:59:48 GMT-0400 (EDT), webkitRelativePath: "", size: 27828905…}
lastModified: 1474084788000
lastModifiedDate: Fri Sep 16 2016 23:59:48 GMT-0400 (EDT)
name: "myfile.mp4"
size: 27828905
type: "video/mp4"
webkitRelativePath: ""
__proto__: File
因此文件加载到video 标签中,我可以观看它。 (代码如下……)
然后,如果我想从硬编码的完整路径加载相同的文件,例如:"file:///path/to/myfile.mp4",则会弹出错误This video file format is not supported.,而我从控制台返回的路径与我完全相同的路径以前是硬编码的。
我的问题是如何通过使用硬编码路径而不是从输入元素中选择文件来加载本地文件?
或
如何直接从本地路径创建 objectURL?
在将文件传递给URL.createObjectURL 函数之前,我已经尝试过Blob,但除非我做错了什么,否则它没有成功。
渲染函数代码:
render() {
return (
<div>
<input type="file" ref="input" onChange={this.upload} />
<video ref="video" type="video/mp4" controls loop autoPlay width="720"></video>
<div ref="message"></div>
</div>
);
}
功能:
processs = (file) => {
let fileURL = URL.createObjectURL(file);
this.refs.video.src = fileURL;
}
playFile = (event) => {
let file = event.target.files[0];
console.log(file);
//check if video can be played
if(this.refs.video.canPlayType(file.type) != ""){
this.processs(file);
} else {
this.refs.message.innerHTML = "This video file format is not supported."
}
};
【问题讨论】:
-
“从硬编码的完整路径加载同一个文件”是什么意思?将
<video>元素src设置为html? -
在反应中,我没有从输入元素将文件作为
const file = event.target.files[0]传递,而是在构造函数中创建了一个this.state({myfile: "file:///fullpath/to/myfile.mp4"})并将其称为const file = this.state.myfile -
您可以使用
XMLHttpRequest()请求本地文件为Blob
标签: javascript html fileapi