Heim > Web-Frontend > js-Tutorial > Hauptteil

Ajax-Datei: Asynchrone Implementierung des Formular-Uploads

php中世界最好的语言
Freigeben: 2018-03-31 10:05:07
Original
1676 Leute haben es durchsucht

Dieses Mal werde ich Ihnen die asynchrone Implementierung des Formular-Uploads mit einer Ajax-Datei vorstellen. Was sind die Vorsichtsmaßnahmen für die asynchrone Implementierung des Formular-Uploads mit einer Ajax-Datei? .

Benutzer-Uploads sind in Projekten immer unverzichtbar. Hier finden Sie die Hauptliste der Formular-Uploads und Ajax-Uploads! Hinweis: context.Request.Files ist nicht für den Betrieb großer Dateien geeignet. Die folgende Liste behandelt hauptsächlich kleine Datei-Uploads !

Ressourcen-Download:

1. Offizielle jQuery-Download-Adresse: https://jquery.com/download/

1 🎜>

HTML-Client-Teil:

<form action="upload.ashx" method="post" enctype="multipart/form-data">
    选择文件:<input type="file" name="file1" /><br />
    <input type="submit" value="上传" />
  </form>
Nach dem Login kopieren
Allgemeiner Handler auf der Serverseite:

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

/// <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);
    }
Nach dem Login kopieren

2. Ajax-Datei-Upload:

Hinweis: Da es einen Formular-Upload gibt, warum benötigen Sie einen Ajax-Upload? Denn während des Formular-Upload-Vorgangs wird die gesamte Seite aktualisiert! Der asynchrone Ajax-Upload kann nur die lokale Position aktualisieren. Werfen wir einen kurzen Blick auf den Ajax-Upload!

HTML-Client-Teil:

<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>
Nach dem Login kopieren
Allgemeiner Handler auf der Serverseite:

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", "请选择要上传的文件");
   }
  }
Nach dem Login kopieren
JSON-Code-Kapselung:

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);
    }
Nach dem Login kopieren
Ob Sie es glauben oder nicht Nachdem Sie den Fall in diesem Artikel gelesen haben, beherrschen Sie die Methode. Weitere spannende Informationen finden Sie in anderen verwandten Artikeln auf der chinesischen PHP-Website!

Empfohlene Lektüre:

Wie fügt AjaxFileUpload dynamisch eine Datei-Upload-Box hinzu?

Eine praktische Zusammenfassung von Ajax und JSONP in das Projekt

Das obige ist der detaillierte Inhalt vonAjax-Datei: Asynchrone Implementierung des Formular-Uploads. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Verwandte Etiketten:
Quelle:php.cn
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!