ajax - IOS6 和 Safari 照片上传 - 文件 API + Canvas + jQuery Ajax 异步上传和调整文件大小

标签 ajax jquery ios6 fileapi

IOS6已经发布,我一直在测试照片上传。

它运行良好,但对于超过 3G 的较大图像,它的速度如预期的那样慢。

借助 File API 和 Canvas,可以使用 JavaScript 调整图像大小。我希望,如果我在尝试上传图像之前调整图像大小,它们的上传速度会更快,从而提供快速的用户体验。随着智能手机处理器的改进速度快于网络速度,我相信该解决方案是赢家。

Nicolas 提供了一个出色的图像调整解决方案:

Image resize before upload

但是,我在使用 jQuery 的 Ajax 实现它时遇到了最困难的时候。感谢任何建议或帮助,因为此代码可能对于 IOS6 后的移动 Web 应用程序开发非常有用。

var fileType = file.type,
    reader = new FileReader();

reader.onloadend = function () {
    var image = new Image();
    image.src = reader.result;

    image.onload = function () {

        //Detect image size
        var maxWidth = 960,
            maxHeight = 960,
            imageWidth = image.width,
            imageHeight = image.height;
        if (imageWidth > imageHeight) {
            if (imageWidth > maxWidth) {
                imageHeight *= maxWidth / imageWidth;
                imageWidth = maxWidth;
            }
        } else {
            if (imageHeight > maxHeight) {
                imageWidth *= maxHeight / imageHeight;
                imageHeight = maxHeight;
            }
        }

        //Create canvas with new image
        var canvas = document.createElement('canvas');
        canvas.width = imageWidth;
        canvas.height = imageHeight;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(this, 0, 0, imageWidth, imageHeight);

        // The resized file ready for upload
        var finalFile = canvas.toDataURL(fileType);

        if (formdata) {

            formdata.append("images[]", finalFile);

            $.ajax({
                url: "upload.php",
                type: "POST",
                data: formdata,
                dataType: 'json',
                processData: false,
                contentType: false,
                success: function (res) {
                    //successful image upload
                }
            });

        }
    }
}
reader.readAsDataURL(file);

最佳答案

我刚刚开发了一个用于客户端 canvas 图像大小调整的 jQuery 插件。 它还可以处理方向iOS6 挤压图像问题。

您可以尝试: http://gokercebeci.com/dev/canvasresize

用法:

$.canvasResize(file, {
               width   : 300,
               height  : 0,
               crop    : false,
               quality : 80,
               callback: function(dataURL, width, height){

                         // your code

               }
});

关于ajax - IOS6 和 Safari 照片上传 - 文件 API + Canvas + jQuery Ajax 异步上传和调整文件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12539862/

相关文章:

jQuery .ajax 请求没有任何效果

JavaScript 函数顺序

jquery - 延迟 jquery 重定向

ipad - 在 iOS 5.0 和 iOS 6.0 上使用 XCode 4.5 的困惑

iOS - 设置 bundle 中文本字段中小数点键盘的键盘类型

javascript - 如何从异步调用返回响应?

javascript - 在 php 键中使用右方括号

javascript - 在 .net 中使用 ajax 切换不处理动态内容的数据

javascript - 根据链接#扩展显示动画

ios - NSURLConnection 在 iOS 6 上超时但在 iOS 5 上不超时