溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

asp.net如何使用H5新特性實(shí)現(xiàn)異步上傳

發(fā)布時(shí)間:2021-06-17 15:47:10 來源:億速云 閱讀:142 作者:小新 欄目:開發(fā)技術(shù)

小編給大家分享一下asp.net如何使用H5新特性實(shí)現(xiàn)異步上傳,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!

###index.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <script src="Script/jquery-1.10.2.min.js"></script>
  <script src="Script/index.js"></script>
  <title></title>
  <script type="text/javascript">
    $(function(){
      $("#ajaxFileUpload").click(function () {
        formDataUpload();
      });
    });
  </script>
</head>
<body>
  <input type="file" id="FileToUpload" multiple="multiple" mame="FileToUpload" />
  <input type="button" id="ajaxFileUpload" value="上傳"/>
  <input type="text" size="10"/>
</body>
</html>


###index.js

function formDataUpload() {
  //這里可以一次性選中多個(gè)文件
  var fileUpload = document.getElementById("FileToUpload").files;
  if (fileUpload.length == 0) {
    alert("請(qǐng)選中文件再上傳");
    return;
  }
  //html5新特性
  var formdata = new FormData();
  //添加上傳數(shù)據(jù)
  for (var i = 0; i < fileUpload.length;i++){
    formdata.append('files', fileUpload[i]);
  }

  //使用javascript的原生ajax
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.open("post", 'Handler.ashx?method=formDataUpload');
  xmlHttp.onreadystatechange = function () {
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
      alert("上傳成功");
    }
  }
  xmlHttp.send(formdata);
}

###handler.ashx

<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
public class Handler : IHttpHandler {
    
  public void ProcessRequest (HttpContext context) {
    formDataUpload(context);
  }
  public static void formDataUpload(HttpContext context) {
    //獲取到客戶端提交的文件
    HttpFileCollection files = context.Request.Files;
    string msg = string.Empty;
    string error = string.Empty;
    int fileM = 0;
    if (files.Count > 0) {
      for (int i = 0; i < files.Count; i++) {      ;
        String path = @"D:\"+files[i].FileName;
        files[i].SaveAs(path);
        fileM += files[i].ContentLength;
      }
      msg = "上傳成功,文件總大小:" + fileM;
      string res = "{error :'" + error + "',msg:'" + msg + "'}";
      context.Response.Write(res);
      context.Response.End();
    }
  }
  public bool IsReusable {
    get {
      return false;
    }
  }
}

看完了這篇文章,相信你對(duì)“asp.net如何使用H5新特性實(shí)現(xiàn)異步上傳”有了一定的了解,如果想了解更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI