表格中上传图片

在表格中上传图片

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

用正则验证要上传的文件是否是图片,如果是,就提交数据到控制器

 regexImgFilter = /^(?:image\/bmp|image\/png|image\/jpeg|image\/jpg)$/i;
        imgReaderI.onload = function (evt) {
            $("#IimgStudentPicture").attr("src", evt.target.result);
        }
        $("#PaperReceipts").change(function () {
            var imgFile = $("#PaperReceipts").prop("files")[0];
            if (!regexImgFilter.test(imgFile.type)) {
                layer.msg('请选择有效的图片', { icon: 0 });
            }
            else {
                $("#ForImages").ajaxSubmit(function (msg) {
                    if (msg == "success") {
                        tabStockSingleTable.refreshPage();
                        layer.alert("上传成功!", { icon: 1, title: "提示" });
                    }
                    else {
                        layer.alert("上传失败!", { icon: 0, title: "提示" });
                    }
                })
            }
        });

下面是控制器代码,将视图传过来的数据转换成字节,再用字节流格式读取,然后保存到数据库

 public ActionResult TableImagesUploadings(HttpPostedFileBase PaperReceipts, int StockID)
        {
            string strMsg = "fail";
            try
            {
                var dbStock = (from tbStock in myModels.PW_Stock
                               where tbStock.StockID == StockID
                               select tbStock).Single();
                byte[] imgFile = null;
                if (PaperReceipts != null && PaperReceipts.ContentLength > 0)
                {
                    imgFile = new byte[PaperReceipts.ContentLength];
                    PaperReceipts.InputStream.Read(imgFile, 0, PaperReceipts.ContentLength);
                }
                dbStock.PaperReceipts = imgFile;
                myModels.Entry(dbStock).State = System.Data.Entity.EntityState.Modified;
                myModels.SaveChanges();
                strMsg = "success";
            }
            catch (Exception)
            {
                strMsg = "fail";
            }
            return Json(strMsg, JsonRequestBehavior.AllowGet);
        }

要查看图片时,在视图层获取ID,再传到控制器,利用这个ID在数据库中查找数据,然后将二进制的图片读取出来,呈现在视图上,代码见下:

public ActionResult SelectTableImages(int StockID)
        {
            try
            {
                var dbStock = (from tbStock in myModels.PW_Stock
                               where tbStock.StockID == StockID
                               select new
                               {
                                   tbStock.PaperReceipts
                               }).Single();
                byte[] CommodityStockOrderImg = dbStock.PaperReceipts;
                return File(CommodityStockOrderImg, @"image/jpg");
            }
            catch (Exception)
            {
                return Json("fail", JsonRequestBehavior.AllowGet);
            }
        }

猜你喜欢

转载自blog.csdn.net/qq_42881311/article/details/87899841