C# MVC Ajax上传图片及文件 前后端分离测试

2 篇文章 0 订阅
1 篇文章 0 订阅
  • 原始表单同步提交文件
  • 通过jQuery使用ajaxSubmit异步提交文件

原始表单同步提交文件

前端代码

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>测试文件上传</title>
    <style>
        .b1 {
            border: #00f 1px solid;
            width: 300px;
            padding: 10px;
        }
    </style>
</head>

<body>
    <div class="b1">
        <form action="https://localhost:44350/upload/uploadImage" method="post" enctype="multipart/form-data">
            <input type="file" name="myfile" /><br />
            <input type="submit" value="使用原始表单提交,缺点:不能异步" />
        </form>
    </div>
</html>

后端代码

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

namespace MVCDeployDemo.Controllers
{
    public class UploadController : Controller
    {
        public JsonResult uploadImage()
        {
            //从请求中获取文件
            HttpPostedFileBase file2 = Request.Files["myfile"];
            if (file2 != null)
            {
                //设置要保存的文件名
                string name = file2.FileName;
                string relativePath = "Content/uploadImg/" + DateTime.Now.Ticks + name.Substring(name.LastIndexOf("."));//相对路径文件夹
                string filepath = Server.MapPath("~") +"/"+ relativePath;//绝对文件路径
                //保存文件                                                                                            
                file2.SaveAs(filepath);
                //返回状态码和图片保存的路径
                var r = new Result() { code = 200, filepath = relativePath };
                return Json(r, JsonRequestBehavior.AllowGet);
            }
            return Json(500, JsonRequestBehavior.AllowGet);
        }
        class Result
        {
            public int code { get; set; }
            public string filepath { get; set; }
        }
    }
}

通过jQuery使用ajaxSubmit提交文件

前端代码,需要引入jquery.js,jquery.form.js

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>测试文件上传</title>
    <script src="node_modules\jquery\dist\jquery.js" type="text/javascript"></script>
    <script src="http://malsup.github.io/jquery.form.js" type="text/javascript"></script>
    <style>
        .b1 {
            border: #00f 1px solid;
            width: 300px;
            padding: 10px;
        }
    </style>
</head>

<body>
   <div class="b1">
        <form id="mainForm" method="post" enctype="multipart/form-data" class="jsrz_main_information">
            <input type="file" name="myfile">
            <input type="button" id="agreementSub" value="使用ajaxSumbit提交文件">
        </form>
    </div>
    <script>
        window.onload = function () {
            console.log("为upload注册事件");
            $("#agreementSub").on("click", function () {
                $('#mainForm').ajaxSubmit(      //ajax方式提交表单
                    {
                        url: 'https://localhost:44350/upload/uploadImage',
                        type: 'post',
                        beforeSubmit: function () { },
                        success: function (data) {
                            console.log(data);
                        },
                        clearForm: false,//禁止清除表单
                        resetForm: false, //禁止重置表单
                        success: function (data) {
                            if (data.code == 200) {
                                var img = "<img src='https://localhost:44350/" + data.filepath + "'/>";
                                $(".jsrz_main_information").append(img);
                            }
                        }
                    });
            });
        }
    </script>

</html>

后端代码

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

namespace MVCDeployDemo.Controllers
{
    public class UploadController : Controller
    {
        public JsonResult uploadImage()
        {
            //从请求中获取文件
            HttpPostedFileBase file2 = Request.Files["myfile"];
            if (file2 != null)
            {
                //设置要保存的文件名
                string name = file2.FileName;
                string relativePath = "Content/uploadImg/" + DateTime.Now.Ticks + name.Substring(name.LastIndexOf("."));//相对路径文件夹
                string filepath = Server.MapPath("~") +"/"+ relativePath;//绝对文件路径
                //保存文件                                                                                            
                file2.SaveAs(filepath);
                //返回状态码和图片保存的路径
                var r = new Result() { code = 200, filepath = relativePath };
                return Json(r, JsonRequestBehavior.AllowGet);
            }
            return Json(500, JsonRequestBehavior.AllowGet);
        }
        class Result
        {
            public int code { get; set; }
            public string filepath { get; set; }
        }
    }
}

运行测试,选择一个图片文件,上传成功。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值