Home > Article > Web Front-end > JavaScript File API file upload preview_javascript skills
For browser-based applications, accessing local files is a headache. Usually all we can do is to use 3525558f8f338d4ea90ebf22e5cde2bc tag to upload files. The implementation process is: when selecting a file, the value attribute saves the name of the file specified by the user. When the form is submitted, the browser will send the content of the selected file to the server instead of just the file name. Then get the address returned by the server and preview it.
But if one day we want to upload a picture, and after uploading the picture, preview and want to change another picture, we have to upload it to the server first and then preview it. When the network is relatively slow, this is really a hassle.
So sometimes we need to preview before uploading to the server, especially those with cutting functions, such as avatar replacement on Sina Weibo. However, the only thing we can do at present is to use plug-in development or use flash. Since the technical implementation of different browsers is different, in order to make the program support multiple browsers, our program will become very complex and difficult to maintain. Fortunately, there is now File API.
By listening to the change event, we can know the file selected by the user, and add a files collection, which will contain file objects, and each file object corresponds to a file. And all have the following read-only attributes name, size, type, lastModifiedDate.
Take 520df7e7475074d70529ab0c7f6abdd9 as an example, monitor onchange and print its file object:
From this we can know some information about the file format, file name, file size, etc. selected by the user. Therefore, it is easy for us to verify whether the selected documents meet some of our requirements.
In addition, the File API also provides the FileReader type to read data in files.
The FileReader type implements an asynchronous file reading mechanism, similar to XMLHttpRequest, but it reads the file system rather than the remote server. And provides several reading methods:
Read the same local image through the above methods, and print out the information saved in the result attribute for comparison as follows:
readAsText(file,encoding):
readAsDataURL(file):
Through the above comparison, we found that these methods of reading files provide great convenience for flexible processing of file data. For example, reading an image file and saving it as a data URL can be used as a preview function before uploading.
Since the reading process is asynchronous, there are several events in FileReader to handle different situations: progress (whether new data has been read), erro (whether an error has occurred), load (whether the entire file has been read) document).
If the file cannot be read due to various reasons, the error event will be triggered. When the error event is triggered, there will be an attribute code (error code) saved in an object in the error attribute of FileReader.
Example of using FileReader for upload preview:
HTML:
<label class="item_label">上传照片: <span style="width: 100px; height: 100px;border:1px solid #ccc; display:inline-block"><img src="#" id="uploadPreview" style="width: 100%; height: 100%;"></span> <input type="file" name="file" id="postFile" style="width:74px;"> <span id="error_text" style="display: none;">提示</span> </label>
JavaScript:
document.getElementById('postFile').onchange = function() { var val = this.value; var upLoadType = '.jpg,.gif,.bmp,.png';//['.jpg','.gif','.bmp','.png']; //可上传的格式 var fileExt = val.substr(val.lastIndexOf(".")).toLowerCase(); //从字符串中抽出最后一次出现.之后的字符,并且转换成小写 var result = upLoadType.indexOf(fileExt); //查找后缀名是否符合条件,如果符合返回>=0,如果不符合则返回负数; _alertMsg = $('#error_text'); var oFReader = new FileReader(); if (this.files.length === 0) { return; } var oFile = this.files[0]; //如果只有一个文件则只需要访问这个FileList对象中的第一个元素. if (oFile.size / 1024 < 100) { _alertMsg.html("<font style='color:blue'>√</font>").show() }; if (result < 0) { _alertMsg.html("请输入正确格式:" + upLoadType).show(); } else{ _alertMsg.html("<font style='color:blue'>√</font>").show(); }; oFReader.readAsDataURL(oFile); // 开始在后台进行读取操作。当图像文件的所有内容加载后,他们转换成一个data:URL,传递到onload回调函数中 oFReader.onload = function (oFREvent) { //当读取操作成功完成时调用. document.getElementById("uploadPreview").src = oFREvent.target.result; }; };
Effect and returned image URL:
The above is the entire content of this article, I hope it will be helpful to everyone’s study.