2016-09-17 52 views
0

我正在使用反應,但事實依然存在:當我用一個輸入上傳一個本地文件的簡單頁面時,如果我選擇了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?

我已經試過Blob這個文件,然後把它傳遞給URL.createObjectURL函數,但是,除非我做錯了,否則它沒有成功。

渲染功能代碼:

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." 
    } 

    }; 
+0

什麼您_「加載相同的文件,而是從一個硬編碼的完整路徑,而不是」的意思是_ ?在'html'中設置'

+0

在反應中,我只是創建了一個'this.state({myfile:「file:/// fullpath/to/file)作爲'const file = event.target.files [0] myfile.mp4「})'並且將其稱爲'const file = this.state.myfile' –

+0

您可以使用'XMLHttpRequest()'來請求本地文件爲'Blob' – guest271314

回答

0

如何直接從本地路徑創建的ObjectURL?

您可以使用XMLHttpRequestresponseType設置爲"blob"File繼承自Blob,則可以將返回的Blob傳遞給您期望File對象的現有函數。另請參見Loading images from file with Javascript

var request = new XMLHttpRequest(); 
request.responseType = "blob"; 
request.open("GET", "file:///path/to/myfile.mp4"); 
request.onload =() => { 
    // do stuff with `request.response` : `Blob` 
} 
request.send(); 
+0

只支持跨源請求協議方案:http,數據,chrome,chrome擴展,https,chrome擴展資源。 –

+0

@JeanmichelCote你在Answer上試過'javascript'哪些瀏覽器?你讀過鏈接的問題/答案嗎? – guest271314

+0

對不起,我不確定你的意思是... –

相關問題