缩小图像文件的大小以加快上传速度?

时间:2016-10-23 06:51:11

标签: javascript jquery asp.net ajax

我有一个简单的代码,可以使用ajax将文件上传到服务器,但我不知道如何在该过程之前调整图像大小以提高性能。

预览图片代码。

function Preview_Image(index){
    var img = document.createElement("img");
    img.src = window.URL.createObjectURL(filesList[index]);
    $('#loaded-image-frame' + index + ' #preview').html(img);
    img.onload = function () {
        window.URL.revokeObjectURL(img.src);
    }
}

上传图片代码..

function Upload_ResizedImage(index){
    var image = filesList[index]
    var form_data = new FormData();
    form_data.append('file[]', image);
    process = $.ajax({
       url: "ControlPanelAjax.ashx?job=UploadImages,
       type: "POST",
       data: form_data,
       processData: false,
       cache: false,
       contentType: false,
       beforeSend: function (event) { },
       success: function (data, textStatus, jQxhr) {
           if (data != '-1') {
              alert("image uploaded correctly");
           }
           else {
              alert("Error Uploading..");
           }
       },
       complete: function (event) {},
       error: function (jqXhr, textStatus, errorThrown) {},
       xhr: function () {}
   });
}

注意:filesList是一个包含我组成的文件的数组

1 个答案:

答案 0 :(得分:0)

您可以使用HTML5中的画布来实现此目的。这是a tutorial,这是相关代码

HTML:

if (window.File && window.FileReader && window.FileList && window.Blob) {
    document.getElementById('filesToUpload').onchange = function(){
        var files = document.getElementById('filesToUpload').files;
        for(var i = 0; i < files.length; i++) {
            resizeAndUpload(files[i]);
        }
    };
} else {
    alert('The File APIs are not fully supported in this browser.');
}

function resizeAndUpload(file) {
var reader = new FileReader();
    reader.onloadend = function() {

    var tempImg = new Image();
    tempImg.src = reader.result;
    tempImg.onload = function() {

        var MAX_WIDTH = 400;
        var MAX_HEIGHT = 300;
        var tempW = tempImg.width;
        var tempH = tempImg.height;
        if (tempW > tempH) {
            if (tempW > MAX_WIDTH) {
               tempH *= MAX_WIDTH / tempW;
               tempW = MAX_WIDTH;
            }
        } else {
            if (tempH > MAX_HEIGHT) {
               tempW *= MAX_HEIGHT / tempH;
               tempH = MAX_HEIGHT;
            }
        }

        var canvas = document.createElement('canvas');
        canvas.width = tempW;
        canvas.height = tempH;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(this, 0, 0, tempW, tempH);
        var dataURL = canvas.toDataURL("image/jpeg");

        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(ev){
            document.getElementById('filesInfo').innerHTML = 'Done!';
        };

        xhr.open('POST', 'uploadResized.php', true);
        xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        var data = 'image=' + dataURL;
        xhr.send(data);
      }

   }
   reader.readAsDataURL(file);
}

PHP:

if ($_POST) {
    define('UPLOAD_DIR', 'uploads/');
    $img = $_POST['image'];
    $img = str_replace('data:image/jpeg;base64,', '', $img);
    $img = str_replace(' ', '+', $img);
    $data = base64_decode($img);
    $file = UPLOAD_DIR . uniqid() . '.jpg';
    $success = file_put_contents($file, $data);
    print $success ? $file : 'Unable to save the file.';
}