欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

MVC学习之六_____上传单张图片

程序员文章站 2022-03-12 21:39:10
...
模板页代码:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>上传图片</title>
</head>
<body>
    <div> 
        <div class="leftImage">
            <input type="file" id="picAjax" class="customButton" />
            <span id="uploadInfo"></span>
            <input type="button" id="submitPic" class="customButton" value="上传" />
        </div>
        <div class="rightImage">
            <img id="selImg" src="" alt="" />
        </div>
    </div>
    <script type="text/javascript" src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script type="text/javascript">
        //选择图片事件
        var picString = "";
        var id = 11;
        $("#picAjax").change(function (e) {
            var file = e.delegateTarget.files[0];
              if (file.type == 'image/jpeg' || file.type == 'image/png') {
                    $("#uploadInfo").text("图片格式正确,请点击提交按钮");
                    var reader = new FileReader();
                    reader.readAsDataURL(file);
                        reader.onload = function (ret)
                        {
                        picString = reader.result;
                         //预览图片
                         $("#selImg").attr({ "src": picString });
                    }
              }
              else {
                    $("#uploadInfo").text("请上传jpg或png格式的图片!");
              }
        });

        //上传图片事件
        $("#submitPic").click(function () {
            if (picString != "") {
                $.ajax("../BasicData/UploadPhoto", {
                    type: "post",
                    datatype: "json",
                    data: {
                        picString:picString,
                        id:id
                    },
                    error: function () { },
                    success: function (result) {
                        if (result.suc == true) {
                            $("#uploadInfo").text("图片上传成功!");
                            $("#ImageList").empty();
                            ReadPicture();
                        }
                    }
                });
            }
        });
    </script>
</body>
</html>




后台代码:
#region 模板页视图
        public ActionResult UploadPhoto()
        {
            return View();
        }
        #endregion

        #region 接收上传图片
        [HttpPost]
        public ActionResult UploadPhoto(string picString, string id)
        {
            var tmpArr = picString.Split(',');
            byte[] bytes = Convert.FromBase64String(tmpArr[1]);
            MemoryStream ms = new MemoryStream(bytes);
            ms.Write(bytes, 0, bytes.Length);
            var img = Image.FromStream(ms, true);

            var path = System.AppDomain.CurrentDomain.BaseDirectory;
            var imagesPath = System.IO.Path.Combine(path, @"Uploads\AgrCorporations\" + id + "\\");
            if (!System.IO.Directory.Exists(imagesPath))
                System.IO.Directory.CreateDirectory(imagesPath);
            string fileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", System.Globalization.DateTimeFormatInfo.InvariantInfo) + ".png";
            var bitImage = GetThumbnailImage(img, 400, 300);
            bitImage.Save(imagesPath + fileName);
            bool isOk = true;
            string msg = imagesPath + fileName;
            return Json(new { suc = isOk, msg = msg });
        }


        #endregion

        #region  图片压缩方法
        /// <summary>
        /// 图片压缩方法
        /// </summary>
        /// <param name="srcImage">Image图片</param>
        /// <param name="width">要压缩的图片宽</param>
        /// <param name="height">要压缩的图片高</param>
        /// <returns></returns>
        private static Image GetThumbnailImage(Image srcImage, int width, int height)
        {
            Image bitmap = new Bitmap(width, height);
            Graphics g = Graphics.FromImage(bitmap);

            //设置高质量插值法 
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighSpeed;

            //在指定位置并且按指定大小绘制原图片的指定部分 
            g.DrawImage(srcImage, new Rectangle(0, 0, width, width),
                new Rectangle(0, 0, srcImage.Width, srcImage.Height),
                GraphicsUnit.Pixel);

            return bitmap;
        }
        #endregion



参考:https://www.cnblogs.com/sharealex/articles/8086595.html
原博客中还有删除及查看的方法,可自己学习
相关标签: mvc