移动端上传图片前端压缩,获取input type=file路径

前端代码

 <script type="text/javascript">
        function readFiles(evt) {
            var files = evt.target.files;
            //console.log(files.length);
            if (!files) {
                alert("文件不支持");
                return;
            }
            var thesrc = window.URL.createObjectURL(files[0]); 
            appendFile(thesrc)
        }
        function appendFile(path) {
            var img = new Image();
            img.src = path;
 
            img.onload = function () {
                var that = this;
                //生成比例
                var w = that.width,
                h = that.height,
                scale = w / h;
                w = 480 || w;
                h = w / scale;
                //生成canvas
                var canvas = document.createElement('canvas');
                var ctx = canvas.getContext('2d');
                $(canvas).attr({ width: w, height: h });
                ctx.drawImage(that, 0, 0, w, h);
                var base64 = canvas.toDataURL('image/jpeg', 1 || 1);
                base64 = base64.replace(/[+]/g, "%2B");
                console.info(base64)
               upload(base64);
            }
        }


        function upload(base64) {
            $.ajax({
                type: "Post",
                url: "/Upload2.ashx",
                data: { imageData: base64, type: "image/jpeg" },
                dataType: "json",
                success: function (data) {
                    
                }
            });
        }

    </script>

后端代码

 

            string base64 = context.Request.Params["imagefile"];

            string data = context.Request.Form["imageData"];
            string strData = data.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)[1];

            //图片的路径
            string basePath = AppDomain.CurrentDomain.BaseDirectory;
            string dirName = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString();
            string dirChildName = DateTime.Now.Day.ToString();
            string imagePath = String.Format(@"Upload\{0}\{1}", dirName, dirChildName);
            string path = Path.Combine(basePath, imagePath);
            Directory.CreateDirectory(path);

            strData = strData.Replace("%2B", "+");
            byte[] arr = Convert.FromBase64String(strData);
            MemoryStream ms = new MemoryStream(arr);
            Bitmap bmp = new Bitmap(ms);
            string imageName = DateTime.Now.Ticks + ".jpg";
            string savePath = Path.Combine(path, imageName);
            bmp.Save(savePath, ImageFormat.Jpeg);
            ms.Close();
            //将路径前加一个\
            //imagePath = "\" + imagePath;
            imagePath = imagePath.Replace('\\', '/');

 

posted @ 2016-02-17 16:49  今天起个早  阅读(1047)  评论(0编辑  收藏  举报