MVC——无刷新上传图片

jquery.form.js 无刷新上传

控制器

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Gzh.MvcWeb.Controllers
{
    public class UploadController : Controller
    {
        // GET: Upload
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 处理单张图片上传
        /// </summary>
        /// <param name="upImg"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UploadImage(HttpPostedFileBase upImg)
        {
            string pic = "", error = "";
            try
            {
                if (upImg != null)
                {
                    string fileName = System.IO.Path.GetFileName(upImg.FileName); //获取上传的文件名
                    string fileExt = Path.GetExtension(fileName);//获取扩展名

                    if (Exist(fileExt))
                    {
                        string virtualPath;
                        string filePath;
                        PerSave(fileName, out virtualPath, out filePath);
                        upImg.SaveAs(filePath);
                        pic = virtualPath;
                    }
                    else
                    {
                        error = "格式不正确";
                    }
                }
                else
                {
                    error = "请选择图片";
                }
            }
            catch (Exception e)
            {
                 //log
                error = "程序出错";
            }

            return Json(new
            {
                pic = pic,
                error = error
            });
        }

        /// <summary>
        /// 预上传,生产文件保存的真实路径和虚拟路径
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="virtualPath"></param>
        /// <param name="filePath"></param>
        private void PerSave(string fileName, out string virtualPath, out string filePath)
        {
            string datafolder = "/upload/" + DateTime.Now.Year.ToString() + ("0" + DateTime.Now.Month.ToString()).Substring(("0" + DateTime.Now.Month.ToString()).Length - 2, 2) + "/"; //文件夹
            string newFileName = DateTime.Now.Ticks.ToString() + "_" + fileName;  //新的文件名
            virtualPath = datafolder + newFileName; //虚拟路径
            filePath = Server.MapPath(virtualPath); //文件保存的地址

            if (!Directory.Exists(Path.GetDirectoryName(filePath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(filePath));
            }
        }


        /// <summary>
        /// 判断后缀
        /// </summary>
        /// <param name="ext"></param>
        /// <returns></returns>
        private bool Exist(string ext)
        {
            bool b = false;
            ArrayList list = new ArrayList() { ".jpeg", ".jpg", ".png", ".gif" };
            if (list.Contains(ext))
            {
                b = true;
            }

            return b;

        }

    }
}

前端代码

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>mvc 无刷新 上传图片</title>
    <style type="text/css">
        form {
            border: 1px solid #CCC;
            border-radius: 5px;
            padding: 10px;
            margin: 10px 0;
            width: 400px;
            background: #EEE;
        }
    </style>
</head>
<body>
    <h1>mvc 无刷新 上传单张图片</h1>
    <form id="form_upload" action="/Upload/UploadImage" method="post" enctype="multipart/form-data">
        <input name="upImg" type="file" /><input type="submit" value="上传" />
    </form>
    <img alt="" style="display:none;" id="result" src="" />

</body>
</html>


<script src="~/Scripts/jquery-2.1.3.min.js"></script>
<script src="~/Scripts/jquery.form.js"></script>
<script type="text/javascript">
    $(function () {
        var options = {
            success: function (responseText, statusText, xhr, $form) {
                var picPath = responseText.pic;
                if (picPath == "") {
                    alert(responseText.error);
                }
                else {
                    $("#result").attr("src", picPath).show();
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log(textStatus);
                console.log(errorThrown);
            }
        };

        $("#form_upload").ajaxForm(options);
    });
</script>


效果 (上传时候页面并不会刷新)

这里写图片描述

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值