用户登录
用户注册

分享至

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

  • 作者: 卖刀了
  • 来源: 51数据库
  • 2021-08-11

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

资源下载:

一、jquery官方下载地址: 

一.表单上传:

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);
    }

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

软件
前端设计
程序设计
Java相关