This is the 27th day of my participation in the August Genwen Challenge.More challenges in August
Image video local preview method
Sometimes, when we upload files, we need to do a local preview first, the following is a common method of local preview
- File gets the file first
var file = document.getElementById("video").files[0]
Copy the code
1. Get the local URL
function getFileURL(file) { var getUrl = null; if (window.createObjectURL ! = undefined) { // basic getUrl = window.createObjectURL(file); } else if (window.URL ! = undefined) { // mozilla(firefox) getUrl = window.URL.createObjectURL(file); } else if (window.webkitURL ! = undefined) { // webkit or chrome getUrl = window.webkitURL.createObjectURL(file); } return getUrl; } var url = getFileURL(file)Copy the code
2, get the base64-bit string of the local resource
Function getpreviewFile(file,ballBack) {var reader = new FileReader(); reader.addEventListener("load", function () { ballBack && ballBack(reader.result) }, false); if (file) { reader.readAsDataURL(file); }} // Use getpreviewFile(file,(url)=>{console.log(url,' returned URL ')});Copy the code
Matters needing attention
URL.createObjectURL()
The url.createObjecturl () static method creates a DOMString with a URL representing the object given in the argument. The lifecycle of this URL and the Document binding in the window that created it. This new URL object represents the specified File object or Blob object.
FileReader
The FileReader object allows a Web application to asynchronously read the contents of a File (or raw data buffer) stored on the user’s computer, using a File or Blob object to specify which File or data to read.
The File object can be a FileList object returned by the user after selecting a File on an element, or it can be generated by a drag-and-drop operation DataTransfer object, which can also be returned from mozGetAsFile() on an HTMLCanvasElement.
Important: FileReader is only used to read file contents from the user’s (remote) system in a secure manner. It cannot be used to simply read files by pathname from the file system. To read files by pathname in JavaScript, you should use a standard Ajax solution for server-side file reading, or CORS permissions if reading crosses domains.