양식 업로드의 ajax 파일 비동기 구현

php中世界最好的语言
풀어 주다: 2018-03-31 10:05:07
원래의
1676명이 탐색했습니다.

이번에는 ajax 파일을 이용한 양식 업로드의 비동기 구현에 대해 알려드리겠습니다. ajax 파일을 이용한 양식 업로드의 비동기 구현에 대한 주의사항은 무엇입니까? 다음은 실제 사례입니다.

사용자 업로드는 항상 프로젝트에 없어서는 안 될 요소입니다. 양식 업로드 및 Ajax 업로드의 주요 목록은 다음과 같습니다. 참고: context.Request.Files는 대용량 파일 작업에 적합하지 않습니다. 다음은 주로 작은 파일 업로드를 처리하는 데 사용됩니다.

리소스 다운로드 :

1. jQuery 공식 다운로드 주소 : https://jquery.com/download/

1. 폼 업로드 :

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);
    }
로그인 후 복사

2. 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);
    }
로그인 후 복사

이 기사의 사례를 읽으신 후 방법을 마스터하셨다고 생각합니다. 더 흥미로운 정보를 보려면 다른 부분에 주의하세요. PHP 중국어 웹사이트에 관련 기사가 있습니다!

추천 자료:

AjaxFileUpload가 파일 업로드 상자를 동적으로 추가하는 방법

프로젝트의 Ajax 및 jsonp에 대한 실제 요약

위 내용은 양식 업로드의 ajax 파일 비동기 구현의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!