天天看點

移動端上傳圖檔前端壓縮,擷取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('\\', '/');      

轉載于:https://www.cnblogs.com/jt789/p/5195879.html

繼續閱讀