本文介绍了新的FileReader API和DataURL的JavaScript预览看起来效率低下的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用新的FileReader API在上传之前预览图像。这是使用DataURL完成的。但是如果图像很大,DataURL可能很大。这对我来说尤其是一个问题,因为用户可能一次上传多张图片,而预览这些图片实际上已经大大减慢了我的浏览器的速度,并且实际上几次撞上了Chrome浏览器。



有没有其他的选择使用DataURL在上传之前预览客户端上的图像?

解决方案

您也可以将数据存储在客户端磁盘(在另一个位置,以便您可以使用JavaScript访问该文件)。这篇文章是相当广泛的,当涉及到这个问题:





所有浏览器都不支持然后创建一个文件,向其中写入数据,最后获取URL:



您必须请求存储空间(文件系统) (fs){
fs.root.getFile(filename,fs){

$ $ p $ window.requestFileSystem(window.PERSISTENT,5 * 1024 * 1024) {create:true},function(fileEntry){
fileEntry.createWriter(function(fileWriter){
var arr = new Uint8Array(data.length);

// fill arr中的图像字节数据

var builder = new BlobBuilder();
builder.append(arr.buffer);
var blob = builder.getBlob();

fileWriter.write(blob);

location.href = fileEntry.toURL(); //导航到文件。该URL不包含数据,但仅包含路径和文件名。
});
});
},function(){});


I am using the new FileReader API to preview images before upload. This is done using DataURLs. But DataURLs can be massive if the images are large. This is especially a problem for me as the user may upload multiple images at a time and previewing the bunch has actually slowed my browser considerably and actually crashed chrome a few times.

Is there any alternative to using DataURLs for previewing images on the client before upload?

解决方案

You can also store data on the client's disk (in another location so that you can access the file using JavaScript). This article is quite extensive when it comes to this subject:

http://www.html5rocks.com/en/tutorials/file/filesystem/

It's not supported on all browsers though.

You have to request storage space (the file system), then create a file, write data to it, and finally fetch the URL:

window.requestFileSystem(window.PERSISTENT, 5*1024*1024, function(fs) {
    fs.root.getFile(filename, {create: true}, function(fileEntry) {
        fileEntry.createWriter(function(fileWriter) {
            var arr = new Uint8Array(data.length);

            // fill arr with image byte data here

            var builder = new BlobBuilder();
            builder.append(arr.buffer);
            var blob = builder.getBlob();

            fileWriter.write(blob);

            location.href = fileEntry.toURL(); // navigate to file. The URL does not contain the data but only the path and filename.
        });
    });
}, function() {});

这篇关于新的FileReader API和DataURL的JavaScript预览看起来效率低下的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 23:31