HTML5 Canvas前台压缩图片并上传到服务器

1.前台代码:

    <input id="fileOne" type="file" />
    <input id="btnOne" value="上传到服务器"  type="button"/>
    <canvas id="canvasOne"  width="1000" height="800"></canvas>
    <script>
        //读取本地文件
        var inputOne = document.getElementById('fileOne');
        inputOne.onchange = function () {
            //1.获取选中的文件列表
            var fileList = inputOne.files;
            var file = fileList[0];
            //读取文件内容
            var reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = function (e) {
                //将结果显示到canvas
                showCanvas(reader.result);
            }
        }
        var canvas = document.getElementById('canvasOne');
        var ctx = canvas.getContext('2d');
        //指定图片内容显示
        function showCanvas(dataUrl) {
            //加载图片
            var img = new Image();
            img.onload = function () {
                //缩小图片
                //ctx.scale(0.5, 0.5);
                ctx.drawImage(img, 0, 0, img.width, img.height);
            }
            img.src = dataUrl;
        }
        //将Canvas图片数据上传到服务器
        /*
        * 图片格式说明,存储图片大小 png > jpg> jpeg
        */
        $('#btnOne').on({
            click: function () {
                //1.获取canvas中的图片数据
                //var data = canvas.toDataURL('image/jpeg',0.2);
                var data = canvas.toDataURL('image/jpeg');
                data = data.split(',')[1];
                //数据格式转换
                data = window.atob(data);
                var ia = new Uint8Array(data.length);
                for (var i = 0; i < data.length; i++) {
                    ia[i] = data.charCodeAt(i);
                }
                var blob = new Blob([ia], { type: 'image/jpeg' });
                //2.提交到服务器
                var fd = new FormData();
                fd.append('file', blob);

                //提交到服务器
                var xhr = new XMLHttpRequest();
                xhr.open('post', '../ashx/upload.ashx', true);
                xhr.onreadystatechange = function () {
                    if (xhr.readyState == 4 && xhr.status == 200) {
                        var data = eval('(' + xhr.responseText + ')');
                        if (data.success == true) {
                            //上传成功
                            var imgName = data.msg;
                            alert(imgName);
                        } else {
                            alert(data.msg);
                        }
                    } else {
                        //alert(xhr.readyState);
                    }
                }
                xhr.send(fd);
            }
        });
        
    </script>

2.后台代码:

/// <summary>
/// 接收二进制上传的图片
/// </summary>
/// <returns></returns>
public string UploadImg()
{
    HttpRequest req = _Context.Request;
    if (req.Files.Count > 0)
    {
        string newname = Guid.NewGuid().ToString() + ".jpg";
        //接收二级制数据并保存
        Stream stream = req.Files[0].InputStream;
        byte[] dataOne = new byte[stream.Length];
        stream.Read(dataOne, 0, dataOne.Length);
        FileStream fs = new FileStream(TempFile + newname, FileMode.Create, FileAccess.Write);
        try
        {
            fs.Write(dataOne, 0, dataOne.Length);
        }
        finally
        {
            fs.Close();
        }
        return newname;
    }
    return "";
}

posted @ 2016-01-05 09:32  天马3798  阅读(3019)  评论(0编辑  收藏  举报