• 企业400电话
  • 微网小程序
  • AI电话机器人
  • 电商代运营
  • 全 部 栏 目

    企业400电话 网络优化推广 AI电话机器人 呼叫中心 网站建设 商标✡知产 微网小程序 电商运营 彩铃•短信 增值拓展业务
    表单上传功能实现 ajax文件异步上传

    项目中用户上传总是少不了的,下面就主要的列举一下表单上传和ajax上传!注意: context.Request.Files不适合对大文件进行操作,下面列举的主要对于小文件上传的处理!

    资源下载:

    一、jQuery官方下载地址:https://jquery.com/download/ 

    一.表单上传:

    html客户端部分:

    form action="upload.ashx" method="post" enctype="multipart/form-data">
        选择文件:input type="file" name="file1" />br />
        input type="submit" value="上传" />
      /form>
    

    一般处理程序服务器端:

    public void ProcessRequest(HttpContext context)
        {
          context.Response.ContentType = "text/plain";
          HttpPostedFile file1 = context.Request.Files["file1"];
          helper.uploadFile(file1, "~/upload/");//这里就是对相应方法进行调用
          context.Response.Write("ok");//提示执行成功
        }
    

    上传代码的封装:

    /// summary>
        /// 上传图片
        /// /summary>
        /// param name="file">通过form表达提交的文件/param>
        /// param name="virpath">文件要保存的虚拟路径/param>
        public static void uploadImg(HttpPostedFile file,string virpath)
        {     
          if (file.ContentLength > 1024 * 1024 * 4)
          {
            throw new Exception("文件不能大于4M");
          }
          string imgtype = Path.GetExtension(file.FileName);
          if(imgtype!=".jpg"imgtype!=".jpeg") //图片类型进行限制
          {
            throw new Exception("请上传jpg或JPEG图片");
          }
          using (Image img = Bitmap.FromStream(file.InputStream))
          {
            string savepath = HttpContext.Current.Server.MapPath(virpath+file.FileName);
            img.Save(savepath);
          }
        }
        /// summary>
        /// 上传文件
        /// /summary>
        /// param name="file">通过form表达提交的文件/param>
        /// param name="virpath">文件要保存的虚拟路径/param>
        public static void uploadFile(HttpPostedFile file, string virpath)
        {
          if (file.ContentLength > 1024 * 1024 * 6)
          {
            throw new Exception("文件不能大于6M");
          }
          string imgtype = Path.GetExtension(file.FileName);
          //imgtype对上传的文件进行限制
          if (imgtype != ".zip"  imgtype != ".mp3")
          {
            throw new Exception("只允许上传zip、rar....文件");
          }
          string dirFullPath= HttpContext.Current.Server.MapPath(virpath);
          if (!Directory.Exists(dirFullPath))//如果文件夹不存在,则先创建文件夹
          {
            Directory.CreateDirectory(dirFullPath);
          }
          file.SaveAs(dirFullPath + file.FileName);
        }
    
    

    二.Ajax文件异步上传:

    注明:既然有了表单上传为什么又要ajax上传呢?因为表单上传过程中,整个页面就刷新了!ajax异步上传就可以达到只刷新局部位置,下面就简单看看ajax上传吧!

    html客户端部分:

    head> 
    script src="jquery-2.1.4.js">/script>
     script>
      $(function () {
       $("#upload").click(function () {
        $("#imgWait").show();
        var formData = new FormData();
        formData.append("myfile", document.getElementById("file1").files[0]); 
        $.ajax({
         url: "upload.ashx",
         type: "POST",
         data: formData,
         /**
         *必须false才会自动加上正确的Content-Type
         */
         contentType: false,
         /**
         * 必须false才会避开jQuery对 formdata 的默认处理
         * XMLHttpRequest会对 formdata 进行正确的处理
         */
         processData: false,
         success: function (data) {
          if (data.status == "true") {
           alert("上传成功!");
          }
          if (data.status == "error") {
           alert(data.msg);
          }
          $("#imgWait").hide();
         },
         error: function () {
          alert("上传失败!");
          $("#imgWait").hide();
         }
        });
       });
      });
     /script>
    /head>
    body> 
      选择文件:input type="file" id="file1" />br />
      input type="button" id="upload" value="上传" />
      img src="wait.gif" style="display:none" id="imgWait" /> 
    /body>
    
    
    

    一般处理程序服务器端:

    public void ProcessRequest(HttpContext context)
      {
       context.Response.ContentType = "text/html";
       if (context.Request.Files.Count > 0)
       {
        HttpPostedFile file1 = context.Request.Files["myfile"];
        helper.uploadFile(file1, "~/upload/"); //这里引用的是上面封装的方法
        WriteJson(context.Response, "true", "");
       }
       else
       {
        WriteJson(context.Response, "error", "请选择要上传的文件");
       }
      }

    json代码封装:

    public static void WriteJson(HttpResponse response,
          string status1, string msg1, object data1 = null)
        {
          response.ContentType = "application/json";
          var obj = new { status = status1, msg = msg1, data = data1 };
          string json = new JavaScriptSerializer().Serialize(obj);
          response.Write(json);
        }
    

    以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

    您可能感兴趣的文章:
    • ajax实现异步文件或图片上传功能
    • ajax图片上传,图片异步上传,更新实例
    • ajax 异步上传带进度条视频并提取缩略图
    • Ajax异步文件上传与NodeJS express服务端处理
    • Ajax异步上传文件实例代码分享
    • ajax实现文件异步上传并回显文件相关信息功能示例
    • jquery中的ajax异步上传
    • Ajax表单异步上传文件实例代码(包括文件域)
    • ajax异步实现文件分片上传实例代码
    上一篇:Ajax实现动态加载组合框的实例代码
    下一篇:简单实体类和xml文件的相互转换方法
  • 相关文章
  • 

    © 2016-2020 巨人网络通讯

    时间:9:00-21:00 (节假日不休)

    地址:江苏信息产业基地11号楼四层

    《增值电信业务经营许可证》 苏B2-20120278

    表单上传功能实现 ajax文件异步上传 表单,上传,功能,实现,ajax,