jquery.form 上传文件

 官网:http://jquery.malsup.com/form/#download  下载地址

 

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>UploadFiles</title>
    <script src="~/Scripts/jquery-1.8.2.js"></script>
    <script src="~/Scripts/jquery.form.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#btnsubmit").click(function () {
                $("#form1").ajaxSubmit({
                    success: function (data) {
                        alert(data.url);
                    },
                    error: function (error) { alert(error); },
                    url: '/Default1/UploadFilesPost', /*设置post提交到的页面*/
                    type: "post", /*设置表单以post方法提交*/
                    dataType: "json" /*设置返回值类型为文本*/
                });
            });
        });
    </script>
</head>
<body>
    <form enctype="multipart/form-data" id="form1">
        <input type="file" name="imgfile" />
        <input type="button" id="btnsubmit" value=" 上 传 " />
    </form>
</body>
</html>

 

public ActionResult UploadFilesPost()
{
    var file = Request.Files["imgfile"];
    string path = "/Upload/" + Guid.NewGuid().ToString() + file.FileName;
    file.SaveAs(Request.MapPath(path));
    return Json(new { url=path });
}

 

构建新的表单提交数据(只提交文本域)

 

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>

    <script src="js/jquery-1.8.2.min.js"></script>
    <script src="js/jquery.form.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#form1").submit(function () {

            });

            $("#btnUpload").click(function () {
                //构建新的表单提交数据(只提交文本域)
                var from = $("<form id='formUpload' enctype='multipart/form-data'></form>");
                //from.append($("#FileCtrl").clone());
                var $fileCtrl = $("#FileCtrl");
                from.append($fileCtrl); //获取文件选择控件添加到新表单
                $(this).before($fileCtrl.clone()); //克隆添加到原来表单
                //$(#form1).ajaxSubmit
                from.ajaxSubmit({
                    //提交前的回调函数
                    beforeSubmit: function () {
                        $("#btnUpload").after("<img src='images/loading.gif'  id='loading'/>");
                    },
                    //提交后的回调函数
                    success: function (data) {
                        if (data.status == "ok") {
                            $("#result").html(data.fileName);
                            $("#FileCtrl").val('');
                        }
                        else if (data.status == "error") {
                            alert(data.msg);
                        }
                        $("#loading").remove();
                        //alert(data.url);
                    },
                    error: function (error) { alert(error); },
                    url: '/FileUploadCtrl.ashx', /*设置post提交到的页面*/
                    type: "post", /*设置表单以post方法提交*/
                    dataType: "json" /*设置返回值类型为文本*/
                });
            });
        });
    </script>
</head>
<body>
    <input type="file" id="FileCtrl" name="FileCtrl" />
    <input type="button" value="上传" id="btnUpload" /><br />

    <div id="result"></div>
</body>
</html>

 

 

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;

namespace _9_无刷新上传文件
{
    /// <summary>
    /// FileUploadCtrl 的摘要说明
    /// </summary>
    public class FileUploadCtrl : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            //context.Response.Write("Hello World");
            HttpPostedFile file = context.Request.Files["FileCtrl"];

            //Thread.Sleep(3000);

            //是否上传文件
            if (file==null||file.ContentLength <= 0)
            {
                context.Response.Write(JsonConvert.SerializeObject(new { status = "error",msg="请选择要上传的文件", fileName = "" }));
                return;
            }
            //上传文件大小检测
            if (file.ContentLength > 1024 * 1024)
            {
                context.Response.Write(JsonConvert.SerializeObject(new { status = "error", msg = "上传文件大小不能超过1M", fileName = "" }));
                return;
            }
            //上传文件后缀名检测
            string filename = file.FileName;
            string suffix = Path.GetExtension(filename);
            if (suffix != ".jpg" & suffix != ".jpeg")
            {
                context.Response.Write(JsonConvert.SerializeObject(new { status = "error", msg = "只允许上传jpg文件", fileName = "" }));
                return;
            }

            #region 保存文件
            //重命名:DateTime
            Random ro = new Random();
            filename = string.Format("{0}_{1}_{2}{3}", DateTime.Now.ToString("yyyyMMdd"), ro.Next(1000, 9999), Path.GetFileNameWithoutExtension(filename), suffix);

            //重命名:GUID(全球唯一标识符)推荐!!!
            //filename = string.Format("{0}{1}", Guid.NewGuid().ToString("N"), suffix);

            //创建目录
            string dirPath = DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day;
            string dirFullPath = context.Server.MapPath("~/upload/" + dirPath);
            string fileFullPath = Path.Combine(dirFullPath, filename);
            //如果文件夹不存在,则先创建文件夹
            if (!Directory.Exists(dirFullPath))
            {
                Directory.CreateDirectory(dirFullPath);
            }

            //string filePath = context.Server.MapPath("~/upload") + "/" + filename;

            //保存文件
            file.SaveAs(fileFullPath);
          context.Response.Write(JsonConvert.SerializeObject(new { status = "ok", fileName = filename }));
            #endregion


         

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

 

转载于:https://www.cnblogs.com/linyongqin/articles/6011051.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值