ajax +.net mvc 多图片上传加预览

本文介绍如何在ASP.NET MVC中结合Ajax实现多图片的上传,并在上传过程中进行预览。文章提到后台未对文件类型进行验证,实际应用时需要注意添加类型检查。
摘要由CSDN通过智能技术生成

ajax +.net mvc 多图片上传加预览


@{
    ViewBag.Title = "Index";
    Layout = null;
}

<!DOCTYPE HTML>
<html>

<head>
    <meta charset="UTF-8">
    <title> 上传多张图片</title>

</head>

<body>
    <script src="~/scripts/jquery-3.3.1.js"></script>
    <script type="text/javascript">
            //选择图片,预览
            function xmTanUploadImg(obj) {
    
                var imgTypes = new Array();
                imgTypes[0] = "JPG";
                imgTypes[1] = "ICO";
                imgTypes[2] = "PNG";
           
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
你可以使用 jQuery插件jCrop来对图片进行预览和裁剪,然后使用 ASP.NET MVC的文件上传功能将裁剪后的图片上传到服务器。 以下是大致的实现步骤: 1. 在视图中引入 jCrop 插件和 jQuery 库: ``` <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-jcrop/0.9.15/css/jquery.Jcrop.min.css" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-jcrop/0.9.15/js/jquery.Jcrop.min.js"></script> ``` 2. 在视图中显示待裁剪的图片: ``` <img src="path/to/image" id="crop-image" /> ``` 3. 使用 jCrop 插件初始化图片裁剪: ``` <script> $(function () { $('#crop-image').Jcrop({ aspectRatio: 1, onSelect: updateCoords }); }); function updateCoords(c) { $('#x').val(c.x); $('#y').val(c.y); $('#w').val(c.w); $('#h').val(c.h); }; </script> ``` 4. 添表单元素用于提交裁剪的坐标: ``` <form method="post" action="Upload" enctype="multipart/form-data"> <input type="hidden" name="x" id="x" /> <input type="hidden" name="y" id="y" /> <input type="hidden" name="w" id="w" /> <input type="hidden" name="h" id="h" /> <input type="file" name="file" /> <input type="submit" value="Upload" /> </form> ``` 5. 在控制器中实现文件上传和图片裁剪: ``` [HttpPost] public ActionResult Upload(HttpPostedFileBase file, int x, int y, int w, int h) { if (file != null && file.ContentLength > 0) { var fileName = Path.GetFileName(file.FileName); var filePath = Path.Combine(Server.MapPath("~/Uploads"), fileName); var img = Image.FromStream(file.InputStream); // 裁剪图片 var croppedImg = new Bitmap(w, h); var g = Graphics.FromImage(croppedImg); g.DrawImage(img, new Rectangle(0, 0, croppedImg.Width, croppedImg.Height), new Rectangle(x, y, w, h), GraphicsUnit.Pixel); croppedImg.Save(filePath); return RedirectToAction("Index"); } return View(); } ``` 这样就可以在 ASP.NET MVC 中实现图片预览、裁剪和上传了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值