简体   繁体   English

使用ajax获取所有图像的文件大小并维护其他图像数据

[英]Obtaining filesize of all images using ajax and maintaining additional image data

The goal - To loop through all images on a page and gather a range of information including image name, original width/height, actual width/height, ratio, display property and FILESIZE. 目标-遍历页面上的所有图像并收集一系列信息,包括图像名称,原始宽度/高度,实际宽度/高度,比率,显示属性和FILESIZE。

This is where I am coming unstuck. 这就是我要解脱的地方。 I am looping through all the images, getting all this information (see below). 我正在遍历所有图像,获取所有这些信息(见下文)。 To obtain the filesize, I am running an ajax call using each image url to return the filesize. 为了获得文件大小,我正在使用每个图像URL运行ajax调用以返回文件大小。

My issue comes that I am unable to return each filesize for each image into a variable (like the other variables) to then be able to display in a list on the page. 我的问题是,我无法将每个图像的每个文件大小返回到变量(如其他变量)中,然后才能显示在页面上的列表中。 I have successfully got the filesizes (by console logging) but not using them in any other way. 我已经成功获取了文件大小(通过控制台日志记录),但是没有以其他任何方式使用它们。

Here is where I have got to: 这是我必须去的地方:

/*LOOP THROUGH EMAIL IMAGES*/
$('body').find('img').each(function() {

    elem = $(this);
    /*ACTUAL DIMENSIONS*/
    img = new Image();
    img.src = elem.attr('src');
    actWidth = img.width;
    actHeight = img.height;
    /*HTML DIMENSIONS*/
    iWidth = elem.width();
    iHeight = elem.innerHeight();
    /*IMAGE FILENAME*/
    index = img.src.lastIndexOf("/") + 1;
    filename = img.src.substr(index);
    /*IMAGE RATIO*/
    ratio = (actWidth / actHeight).toFixed(2);
    newRatio = parseFloat(ratio);

    /*FILESIZE*/
    sizeKB = '';

    $.ajax({
        type: 'HEAD',
        url: img.src,
        success: function(data, textStatus, request){

            //THIS IS WHERE I NEED TO COLLECT THE FILESIZE AND PLACE IT IN A VARIABLE THAT CAN BE USED

            console.log(request.getResponseHeader('Content-Length'));

            sizeKB = request.getResponseHeader('Content-Length');
            return sizeKB;
        }
    });

    console.log(
        'Display: '+displayProp+
        ', Name: '+filename+
        ', Actual size: '+actWidth+'x'+actHeight+
        ', Email size:'+iWidth+'x'+iHeight+
        ', Aspect Ratio: '+newRatio+':1'+
        ', Size: '+sizeKB
    );

});

As is stands, when I try to return the sizeKB from the success call back into the console.log with the other data, it is empty. 就目前而言,当我尝试将成功调用中的sizeKB与其他数据一起返回到console.log时,它为空。

Any help would be greatly appreciated 任何帮助将不胜感激

The thing here is you are calling the console.log() synchronously while AJAX works asynchron. 这里的事情是,当AJAX异步工作时,您正在同步调用console.log() That means when you are logging the values you don't really have the image's size as it loads a couple of milliseconds later. 这意味着当您记录这些值时,实际上并没有图像的大小,因为它会在几毫秒后加载。

Just move your console.log into your success function and it will work as you call it when the AJAX is done rather than calling it as before said synchronously. 只需将console.log移到success函数中,它将在您完成AJAX时像调用它一样工作,而不是像之前所说的那样同步调用它。

Your old code will be changed from: 您的旧代码将从以下位置更改:

$.ajax({
    type: 'HEAD',
    url: img.src,
    success: function(data, textStatus, request){

        //THIS IS WHERE I NEED TO COLLECT THE FILESIZE AND PLACE IT IN A VARIABLE THAT CAN BE USED

        console.log(request.getResponseHeader('Content-Length'));

        var sizeKB = request.getResponseHeader('Content-Length');
        return sizeKB;
    }
});

console.log(
    'Display: '+displayProp+
    ', Name: '+filename+
    ', Actual size: '+actWidth+'x'+actHeight+
    ', Email size:'+iWidth+'x'+iHeight+
    ', Aspect Ratio: '+newRatio+':1'+
    ', Size: '+sizeKB
);

to: 至:

$.ajax({
    type: 'HEAD',
    url: img.src,
    success: function(data, textStatus, request){

        //THIS IS WHERE I NEED TO COLLECT THE FILESIZE AND PLACE IT IN A VARIABLE THAT CAN BE USED

        console.log(request.getResponseHeader('Content-Length'));

        var sizeKB = request.getResponseHeader('Content-Length');

        console.log(
            'Display: '+displayProp+
            ', Name: '+filename+
            ', Actual size: '+actWidth+'x'+actHeight+
            ', Email size:'+iWidth+'x'+iHeight+
            ', Aspect Ratio: '+newRatio+':1'+
            ', Size: '+sizeKB
        );
    }
});

Well I did a rough script. 好吧,我做了一个粗糙的剧本。 This will make an object of all the images and its relevant data. 这将成为所有图像及其相关数据的对象。 You can use this data later on where ever you want. 您以后可以在任何需要的地方使用此数据。

 var imagesData = {},
    images = $('body').find('img');

images.each(function() {
    var image = {},
        elem = $(this),
        img = new Image();

    img.src = elem.attr('src');
    var index = img.src.lastIndexOf("/") + 1,
        ratio = (img.width / img.height).toFixed(2);

    image["name"] = img.src.substr(index);
    image["width"] = img.width;
    image["height"] = img.height;
    image["html_width"] = elem.width();
    image["html_height"] = elem.innerHeight();
    image["ratio"] = parseFloat(ratio) + ":1";
    imagesData[img.src] = image

    $.ajax({
        type: 'HEAD',
        url: img.src,
        success: function(data, textStatus, request){
            imagesData[this.url]["size"] = request.getResponseHeader('Content-Length');
        }
    });

});
console.log(imagesData);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用rails 3.2.2中的$ .ajax()异步获取数据 - Obtaining data asynchronously using $.ajax() in rails 3.2.2 jquery.Ajax数据获取 - jquery.Ajax data obtaining 图像滑块:保持所有图像的相同高度,同时保持滑块响应 - Image slider: maintaining equal height for all images while keeping slider responsive 通过ajax方法上传图像之前,请在jQuery中检查文件大小和文件类型 - Check filesize and filetype in Jquery before uploading image via ajax method 在图库中使用Ajax加载图像 - loading images using ajax in an image gallery 当我在ajax图片预览中添加额外的图片时,之前的图片没有出现在输入类型FILES数组中 - When I add additional images to the ajax image preview, the previous ones do not appear in the input type FILES array 使用.replacewith更改图像,但保留id。 之后,该图像不再在悬停时触发功能 - Using .replacewith to change images but maintaining id. After that the image does not fire function on hover anymore AJAX使用jQuery可排序的发布其他数据(非表单) - AJAX posting additional data using jQuery sortable (not form) 如何使用php / ajax在指定的div中附加数据 - How to append additional data in a specified div using php / ajax 使用HTML Canvas + Javascript优化和图像处理+减少文件大小 - Using HTML Canvas + Javascript to optimize and image + reduce filesize
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM