异步上传图片的几种方式

使用jquery.form.js插件实现

  1. HTML页面

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Indextitle>
    <script src="~/Scripts/jquery-3.3.1.js">script>
    <script src="~/Scripts/jquery.form.js">script>
head>
<body>
    <form enctype="multipart/form-data" method="post" id="upload">
        <input type="file" id="fileupload" name="Upload" />
        <input type="button" value="上传图片" id="btn">
        <div id="resultDiv">div>
    form>
    <script>
        $("#btn").click(function () {
            $("#upload").ajaxSubmit({
                url: "../Home/UploadFile",
                type: "post",
                success: function (data) {
                    $("#resultDiv").html("");
                },
                error: function (error) {
                    console.log(error);
                }
            });
            return false;
        });
    script>
body>
html>
  1. 控制器(Controller)
public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult UploadFile()
        {
            HttpPostedFileBase file = Request.Files[0];
            if (file != null)
            {
                string fileName = Path.GetFileName(file.FileName);
                string fileExt = Path.GetExtension(file.FileName);
                string fileNewName = Guid.NewGuid() + fileExt;
                string fileSaveDir = Server.MapPath("~/upload");
                if (!Directory.Exists(fileSaveDir))
                {
                    Directory.CreateDirectory(fileSaveDir);
                }
                file.SaveAs(Path.Combine(fileSaveDir, fileName));
                return new JsonResult
                {
                    Data = new
                    {
                        _code = 200,
                        _msg = "上传成功",
                        _data = new
                        {
                            _url = "/Upload/" + fileName,
                            _oldName = fileName
                        }
                    }
                    ,
                    JsonRequestBehavior = JsonRequestBehavior.DenyGet
                };
            }
            return new JsonResult
            {
                Data = new
                {
                    _code = 200,
                    _msg = "上传失败"
                },
                JsonRequestBehavior = JsonRequestBehavior.DenyGet
            };
        }
    }

你可能感兴趣的:(异步上传图片的几种方式)