Home > php教程 > PHP开发 > body text

jQuery plug-in ajaxFileUpload usage example analysis

高洛峰
Release: 2016-12-09 16:01:44
Original
1219 people have browsed it

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>
Copy after login

Step 2: HTML code:

<body>
 <p><input type="file" id="file1" name="file" /></p>
 <input type="button" value="上传" />
 <p><img id="img1" alt="上传成功啦" src="" /></p>
</body>
Copy after login

Step 3: JS code

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

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();
  }
}
Copy after login

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);
  }
}
Copy after login

Front-end view, HTML and JS code. After successful upload, return the real address of the image and bind it to < img> 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 id="img1" alt="上传成功啦" src="" /></p>
</body>
</html>
Copy after login

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);
  }
}
Copy after login

Index view code:

<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;, //用于文件上传的服务器端请求地址
          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>
Copy after login

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.


Related labels:
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!