<html>
<head>
    <title>图片等比例缩放后上传</title>
    <meta name="viewport" content="width=device-width,initial-scale=1 user-scalable=0">
    <script src="/Scripts/jquery-1.10.2.min.js"></script>
    <script type="text/javascript">
        $(function () {
            function decodeUnicode(str) {
                return unescape(unescape(str.replace(/\\u/g, '%u')));
            }

            $("#pic").change(function () {
                var _this = $(this)[0], _file = _this.files[0], fileType = _file.type;
                console.log(_file.size);
                console.log(_file.type)
                if (/image\/\w+/.test(fileType)) {
                    var fileReader = new FileReader();
                    fileReader.readAsDataURL(_file);
                    fileReader.onload = function (event) {
                        var result = event.target.result;   //返回的dataURL
                        var image = new Image();
                        image.src = result;
                        image.onload = function () {  //创建一个image对象,给canvas绘制使用
                            var cvs = document.createElement('canvas');
                            var scale = 1;
                            var tt = 1000; //只是示例,可以根据具体的要求去设定
                            if (this.width > tt || this.height > tt) {
                                if (this.width > this.height) {
                                    scale = tt / this.width;
                                } else {
                                    scale = tt / this.height;
                                }
                            }
                            cvs.width = this.width * scale;
                            cvs.height = this.height * scale;     //计算等比缩小后图片宽高
                            var ctx = cvs.getContext('2d');
                            ctx.drawImage(this, 0, 0, cvs.width, cvs.height);
                            var newImageData = cvs.toDataURL(fileType, 0.8);   //重新生成图片,fileType为用户选择的图片类型
                            var sendData = newImageData.replace("data:" + fileType + ";base64,", '');

                            $.ajax({
                                url: '/Upload/SavePictureByBase64',
                                type: 'POST',
                                dataType: 'json',
                                data: { sendData: sendData },
                                timeout: 10000,
                                cache: false,
                                beforeSend: function () {
                                    $(".distinguish").show();
                                    $(".resultul").html("").append('<li><img src="/images/loading.gif" /><li>');
                                },
                                success: function (json) {
                                    $(".distinguish").show();
                                    $(".resultul").html("").append('<li><img src="/images/loading.gif" /><li>');
                                    var status = json.status;
                                    var msg = json.msg;
                                    //alert(msg);
                                    if (!status) {
                                        alert(msg);
                                    }
                                    else {

                                        var uploadPath = msg;
                                        //alert("上传成功,图片路径为" + msg);
                                        // 
                                        $.ajax({
                                            url: 'http://www.xxx.com',
                                            type: 'POST',
                                            dataType: 'text',
                                            data: { filePath: uploadPath },
                                            timeout: 9000,
                                            cache: false,
                                            success: function (json) {
                                                //alert(json);
                                                console.log(json);
                                                $(".resultul").html("");
                                                var patt = /\"words\":\"(.*?)\"/gi;
                                                var ret;
                                                while ((ret = patt.exec(json)) != null) {
                                                    //alert(ret[1]);
                                                    console.log(ret[1]);
                                                    //console.log("ret.input=" + ret.input);
                                                    //console.log("ret.index=" + ret.index);
                                                    //console.log("RegExp.lastIndex =" + RegExp.lastIndex);
                                                    if (ret[1] != "unknown") {
                                                        $(".resultul").append("<li>" + decodeUnicode($.trim(ret[1])) + "</li>");
                                                    }
                                                }
                                            },
                                            error: function (data) {
                                                console.log(data.status + " : " + data.statusText + " : " + data.responseText);
                                                alert("发生错误,请重试")
                                            }
                                        });
                                    }
                                },
                                error: function (data) {
                                    console.log(data.status + " : " + data.statusText + " : " + data.responseText);
                                    alert("发生错误,请重试");
                                    $(".distinguish").hide();
                                }
                            });
                        }
                    }
                }
                else {
                    alert("请选择图片上传");
                }
            });
        });

    </script>
    <style type="text/css">
        .distinguish {
            border: 1px solid #eee;
            width: 95%;
            height: auto;
            min-height: 100px;
            text-align: left;
            display: none;
        }

        .upload {
            border: 1px solid #eee;
            padding: 4px 10px;
            height: 20px;
            line-height: 20px;
            position: relative;
            cursor: pointer;
            color: #888;
            background: #fafafa;
            border: 1px solid #ddd;
            border-radius: 4px;
            overflow: hidden;
            display: inline-block;
            *display: inline;
            *zoom: 1;
        }

            .upload input {
                position: absolute;
                font-size: 100px;
                right: 0;
                top: 0;
                opacity: 0;
                filter: alpha(opacity=0);
                cursor: pointer;
            }

            .upload:hover {
                color: #444;
                background: #eee;
                border-color: #ccc;
                text-decoration: none;
            }

        li {
            list-style-type: none;
        }

        #btnPost {
            display: inline-block;
            padding: 7px 15px;
            border-radius: 4px;
            border: 1px solid #eee;
            margin-left: 20px;
            position: relative;
            top: -10px;
        }
    </style>

</head>
<body>
    <h4>上传图片</h4>
    <div class="upload">
        <input id="pic" name="pic" type="file" accept="image/*;capture=camera">选择文件
    </div>
    <h4>结果</h4>
    <div class="distinguish">
        <ul class="resultul"></ul>
    </div>
</body>
</html>
        public ActionResult SavePictureByBase64()
        {
            String fileExt = ".jpg";
            try
            {

                String filename = MSCL.Until.GetGuid() + fileExt;
                String filepath = Server.MapPath(UploadFolder);
                String photoFullName = Path.Combine(filepath, filename);
                //创建写入文件 
                FileStream fs1 = new FileStream(photoFullName, FileMode.Create, FileAccess.Write);
                fs1.Close();

                byte[] arr = Convert.FromBase64String(Request["sendData"]);
                MemoryStream ms = new MemoryStream(arr);
                Bitmap bmp = new Bitmap(ms);
                bmp.Save(photoFullName, System.Drawing.Imaging.ImageFormat.Jpeg);
                ms.Close();
                fs1.Close();
                return Json(new { status = true, msg = string.Format("{0}/{1}/{2}", Url, UploadFolderName, filename) });

            }
            catch (Exception ex)
            {
                return Json(new { status = false, msg = "上传失败" });
            }
        }
        #endregion


本文转载:CSDN博客