In html elements, the only control that can upload files is <input type = "file">,
It is worth noting that when a form contains this upload element, the form's enctype must be specified as multipart/form-data, and the method must be specified as post, the browser will recognize and correctly execute. However, the browser only allows users to click <input type = "file"> to select a local file, using JavaScript to assign values to <input type = "file"> has no effect. After you select to upload a file, JavaScript cannot obtain the actual path of the file:
However, there is a way to obtain the File information and read the File by using two main objects: File and FileReader.
Example file: file-upload-demo.html
HTML file
<Form method = "post" enctype = "multipart/form-data" id = "file_upload">
<P> image preview: </p>
<Div id = "test-image-preview"> </div>
<P>
<Input type = "file" id = "test-image-file" name = "test" accept = "image/gif, image/jpeg, image/png, image/jpg ">
</P> <p id = "test-file-info"> </p> </form>
CSS
#test-image-preview {
border: 1px solid #ccc; width: 100%; height: 200px; background-size: contain; background-repeat: no-repeat; background-position: center center;}
JS
<Script src = "http://cdn.loveqiao.com/jquery.js"> </script> <script type = "text/javascript"> var
FileInput = document. getElementById ('test-image-file'), info = document. getElementById ('test-file-info'), preview = document. getElementById ('test-image-preview'); // listens for the change event: fileInput. addEventListener ('change', function () {// clear the background image: preview. style. backgroundImage = ''; // check whether the file is selected: if (! FileInput. value) {info. innerHTML = 'no selected file'; return;} // get File reference: var file = fileInput. files [0]; // determine the file size var size = file. size; if (size> = 1*1024*1024) {alert ('the file is larger than 1 MB! '); Return false;} // obtain the File information: info. innerHTML = 'file: '+ file. name + '<br>' + 'size:' + file. size + '<br>' + 'modify:' + file. lastModifiedDate; if (file. type! = 'Image/jpeg '& file. type! = 'Image/png '& file. type! = 'Image/gif') {alert ('is not a valid image file! '); Return; // read the file: var reader = new FileReader (); reader. onload = function (e) {var data = e.tar get. result; // 'data: image/jpeg; base64,/9j/4AAQSk... (base64 encoding )...} 'preview. style. backgroundImage = 'url ('+ data +') ';}; // read the file in DataURL format: reader. readAsDataURL (file); console. log (file) ;}); </script>