search
Homephp教程PHP开发jQuery plug-in ajaxFileUpload usage example analysis

AjaxFileUpload.js is not a very famous plug-in. It is just written by others and released for everyone to use. The principle is to create hidden forms and iframes and then use JS to submit them and get the return value.

I originally made an asynchronous upload function and chose it because its configuration method is more like jQuery’s AJAX, which I like very much.

What is said in the comments does not work. That's because we are not using the same js. I searched AjaxFileUpload on github and found a lot of similar js.

ajaxFileUpload is a jQuery plug-in for asynchronous file upload

Upload a version you don’t know, so you don’t have to look for it everywhere in the future.

Syntax: $.ajaxFileUpload([options])

options parameter description:

1, url     Upload handler address. ​
2, fileElementId​​​ The ID of the file field that needs to be uploaded, that is, the ID of .
3, secureuri     Whether to enable secure submission, the default is false.
4, dataType The data type returned by the server. Can be xml, script, json, html. If you don't fill it in, jQuery will automatically determine it.
5, success It is a processing function that is automatically executed after successful submission. The parameter data is the data returned by the server.
6, error    Handling function that is automatically executed when submission fails.
7, data Custom parameters. This thing is more useful. When there is data related to the uploaded image, this thing will be used.
8, type When submitting custom parameters, this parameter must be set to post

Error message:

1. SyntaxError: missing; before statement error
If this error occurs, you need to check whether the url path is accessible
2. SyntaxError: syntax error
If this error occurs, you need to check whether there is a syntax error in the server background handler that handles the submission operation
3. SyntaxError: invalid property id error
If this error occurs, you need to check whether the text field attribute ID exists
4. SyntaxError: missing } in XML expression error
If this error occurs, you need to check whether the file name is consistent or does not exist
5. Other custom errors
You can use the variable $error to print directly to check whether each parameter is correct. It is much more convenient than the above invalid error prompts.

How to use:

Step 1: First introduce the jQuery and ajaxFileUpload plug-ins. Pay attention to the order. Needless to say, this is true for all plug-ins.

<script src="jquery-1.7.1.js" type="text/javascript"></script>
<script src="ajaxfileupload.js" type="text/javascript"></script>

Step 2: HTML code:

<body>
 <p><input type="file" id="file1" name="file" /></p>
 <input type="button" value="上传" />
 <p><img src="/static/imghwm/default1.png"  data-src="jquery-1.7.1.js"  class="lazy"  id="img1" alt="上传成功啦"  /></p>
</body>

Step 3: JS code

<script  type="text/javascript"></script>
<script src="ajaxfileupload.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$(":button").click(function () {
ajaxFileUpload();
})
})
function ajaxFileUpload() {
$.ajaxFileUpload
(
{
 url: &#39;/upload.aspx&#39;, //用于文件上传的服务器端请求地址
 secureuri: false, //是否需要安全协议,一般设置为false
 fileElementId: &#39;file1&#39;, //文件上传域的ID
 dataType: &#39;json&#39;, //返回值类型 一般设置为json
 success: function (data, status) //服务器成功响应处理函数
 {
 $("#img1").attr("src", data.imgurl);
 if (typeof (data.error) != &#39;undefined&#39;) {
 if (data.error != &#39;&#39;) {
 alert(data.error);
 } else {
 alert(data.msg);
 }
 }
 },
 error: function (data, status, e)//服务器响应失败处理函数
 {
 alert(e);
 }
}
)
return false;
}
</script>

Step 4: Backend page upload.aspx code:

protected void Page_Load(object sender, EventArgs e)
{
  HttpFileCollection files = Request.Files;
  string msg = string.Empty;
  string error = string.Empty;
  string imgurl;
  if (files.Count > 0)
  {
    files[0].SaveAs(Server.MapPath("/") + System.IO.Path.GetFileName(files[0].FileName));
    msg = " 成功! 文件大小为:" + files[0].ContentLength;
    imgurl = "/" + files[0].FileName;
    string res = "{ error:&#39;" + error + "&#39;, msg:&#39;" + msg + "&#39;,imgurl:&#39;" + imgurl + "&#39;}";
    Response.Write(res);
    Response.End();
  }
}

Download the complete code of this example

Let’s take an example of the MVC version:

Controller code

public class HomeController : Controller
{
  public ActionResult Index()
  {
    return View();
  }
 
  public ActionResult Upload()
  {
    HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
    string imgPath = "";
    if (hfc.Count > 0)
    {
      imgPath = "/testUpload" + hfc[0].FileName;
      string PhysicalPath = Server.MapPath(imgPath);
      hfc[0].SaveAs(PhysicalPath);
    }
    return Content(imgPath);
  }
}

Front-end view, HTML and JS code. After successful upload, return the real address of the image and bind it to SRC address

<html>
<head>
  <script src="/jquery-1.7.1.js" type="text/javascript"></script>
  <script src="/ajaxfileupload.js" type="text/javascript"></script>
  <script type="text/javascript">
    $(function () {
      $(":button").click(function () {
        if ($("#file1").val().length > 0) {
          ajaxFileUpload();
        }
        else {
          alert("请选择图片");
        }
      })
    })
    function ajaxFileUpload() {
      $.ajaxFileUpload
      (
        {
          url: &#39;/Home/Upload&#39;, //用于文件上传的服务器端请求地址
          secureuri: false, //一般设置为false
          fileElementId: &#39;file1&#39;, //文件上传空间的id属性 <input type="file" id="file" name="file" />
          dataType: &#39;HTML&#39;, //返回值类型 一般设置为json
          success: function (data, status) //服务器成功响应处理函数
          {
            alert(data);
            $("#img1").attr("src", data);
            if (typeof (data.error) != &#39;undefined&#39;) {
              if (data.error != &#39;&#39;) {
                alert(data.error);
              } else {
                alert(data.msg);
              }
            }
          },
          error: function (data, status, e)//服务器响应失败处理函数
          {
            alert(e);
          }
        }
      )
      return false;
    }
  </script>
</head>
<body>
  <p><input type="file" id="file1" name="file" /></p>
  <input type="button" value="上传" />
  <p><img src="/static/imghwm/default1.png"  data-src="/jquery-1.7.1.js"  class="lazy"  id="img1" alt="上传成功啦"  /></p>
</body>
</html>

Finally, here is an example of uploading an image with parameters: Controller code:

public class HomeController : Controller
{
  public ActionResult Index()
  {
    return View();
  }
 
  public ActionResult Upload()
  {
    NameValueCollection nvc = System.Web.HttpContext.Current.Request.Form;
 
    HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
    string imgPath = "";
    if (hfc.Count > 0)
    {
      imgPath = "/testUpload" + hfc[0].FileName;
      string PhysicalPath = Server.MapPath(imgPath);
      hfc[0].SaveAs(PhysicalPath);
    }
    //注意要写好后面的第二第三个参数
    return Json(new { Id = nvc.Get("Id"), name = nvc.Get("name"), imgPath1 = imgPath },"text/html", JsonRequestBehavior.AllowGet);
  }
}

Index view code:

<html>
<head>
  <script  type="text/javascript"></script>
  <script src="/ajaxfileupload.js" type="text/javascript"></script>
  <script type="text/javascript">
    $(function () {
      $(":button").click(function () {
        if ($("#file1").val().length > 0) {
          ajaxFileUpload();
        }
        else {
          alert("请选择图片");
        }
      })
    })
    function ajaxFileUpload() {
      $.ajaxFileUpload
      (
        {
          url: &#39;/Home/Upload&#39;, //用于文件上传的服务器端请求地址
          type: &#39;post&#39;,
          data: { Id: &#39;123&#39;, name: &#39;lunis&#39; }, //此参数非常严谨,写错一个引号都不行
          secureuri: false, //一般设置为false
          fileElementId: &#39;file1&#39;, //文件上传空间的id属性 <input type="file" id="file" name="file" />
          dataType: &#39;json&#39;, //返回值类型 一般设置为json
          success: function (data, status) //服务器成功响应处理函数
          {
            alert(data);
            $("#img1").attr("src", data.imgPath1);
            alert("你请求的Id是" + data.Id + "   " + "你请求的名字是:" + data.name);
            if (typeof (data.error) != &#39;undefined&#39;) {
              if (data.error != &#39;&#39;) {
                alert(data.error);
              } else {
                alert(data.msg);
              }
            }
          },
          error: function (data, status, e)//服务器响应失败处理函数
          {
            alert(e);
          }
        }
      )
      return false;
    }
  </script>
</head>
<body>
  <p><input type="file" id="file1" name="file" /></p>
  <input type="button" value="上传" />
  <p><img id="img1" alt="上传成功啦" src="" /></p>
</body>
</html>

showing While uploading images asynchronously, custom transmission parameters will pop up. The download address of this example

January 28, 2013. During the debugging process today, I discovered a problem, that is, as a file field (), it must have a name attribute. If there is no name attribute, after uploading The server cannot obtain the image. For example: the correct way of writing is

On January 28, 2013, the cause of the most classic error was finally found. Object function (a,b){return new e.fn.init(a,b,h)} has no method 'handleError'. This is an error reported by Google browser. It is very classic. I don’t know if it is a problem with my version or not. The real problem. The root cause of this problem was found after N uploads. The answer is: the dataType parameter must be in uppercase letters. For example: dataType: 'HTML'.

 2016-07-28, an error in the comments: TypeError: $.ajaxFileUpload is not a function We are not using the same JS, you downloaded another AJAXFileUpload.


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
jquery实现多少秒后隐藏图片jquery实现多少秒后隐藏图片Apr 20, 2022 pm 05:33 PM

实现方法:1、用“$("img").delay(毫秒数).fadeOut()”语句,delay()设置延迟秒数;2、用“setTimeout(function(){ $("img").hide(); },毫秒值);”语句,通过定时器来延迟。

axios与jquery的区别是什么axios与jquery的区别是什么Apr 20, 2022 pm 06:18 PM

区别:1、axios是一个异步请求框架,用于封装底层的XMLHttpRequest,而jquery是一个JavaScript库,只是顺便封装了dom操作;2、axios是基于承诺对象的,可以用承诺对象中的方法,而jquery不基于承诺对象。

jquery怎么在body中增加元素jquery怎么在body中增加元素Apr 22, 2022 am 11:13 AM

增加元素的方法:1、用append(),语法“$("body").append(新元素)”,可向body内部的末尾处增加元素;2、用prepend(),语法“$("body").prepend(新元素)”,可向body内部的开始处增加元素。

jquery怎么修改min-height样式jquery怎么修改min-height样式Apr 20, 2022 pm 12:19 PM

修改方法:1、用css()设置新样式,语法“$(元素).css("min-height","新值")”;2、用attr(),通过设置style属性来添加新样式,语法“$(元素).attr("style","min-height:新值")”。

jquery中apply()方法怎么用jquery中apply()方法怎么用Apr 24, 2022 pm 05:35 PM

在jquery中,apply()方法用于改变this指向,使用另一个对象替换当前对象,是应用某一对象的一个方法,语法为“apply(thisobj,[argarray])”;参数argarray表示的是以数组的形式进行传递。

jquery怎么删除div内所有子元素jquery怎么删除div内所有子元素Apr 21, 2022 pm 07:08 PM

删除方法:1、用empty(),语法“$("div").empty();”,可删除所有子节点和内容;2、用children()和remove(),语法“$("div").children().remove();”,只删除子元素,不删除内容。

jquery on()有几个参数jquery on()有几个参数Apr 21, 2022 am 11:29 AM

on()方法有4个参数:1、第一个参数不可省略,规定要从被选元素添加的一个或多个事件或命名空间;2、第二个参数可省略,规定元素的事件处理程序;3、第三个参数可省略,规定传递到函数的额外数据;4、第四个参数可省略,规定当事件发生时运行的函数。

jquery怎么去掉只读属性jquery怎么去掉只读属性Apr 20, 2022 pm 07:55 PM

去掉方法:1、用“$(selector).removeAttr("readonly")”语句删除readonly属性;2、用“$(selector).attr("readonly",false)”将readonly属性的值设置为false。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft