This time I will bring you FormData+Ajax upload progress monitoring (with code). What are the precautions for FormData+Ajax upload progress monitoring? . Here is a practical case, let’s take a look.
What is FormData?
The FormData object can assemble a set of key/value pairs used to send requests using XMLHttpRequest. It makes sending form data more flexible and convenient because it can be used independently of the form. If you set the encoding type of the form to multipart/form-data, the data format transmitted through FormData is the same as the data format transmitted by the form through the submit() method;
How to create a FormData object
You can create a FormData object yourself and then add fields by calling its append() method, like this:
//实例化一个formData对象 var formData = new FormData(); formData.append("username", "Groucho"); formData.append("userid", 123456); // 数字 123456 会被立即转换成字符串 "123456" // HTML上的 文件类型input[type=file]的文件框,由用户选择 formData.append("userfile", fileInputElement.files[0]); // JavaScript file-like 对象 var content = '<a id="a"><b id="b">hey!</b></a>'; // 新文件的正文... var blob = new Blob([content], { type: "text/xml"}); formData.append("webmasterfile", blob);
Note: The field "userfile " and "webmasterfile" both contain a file. The field "userid" is of numeric type, which will be converted to a string type by the FormData.append() method (the field type of the FormData object can be Blob, File, or string: If its If the field type is not Blob or File, it will be converted to a string type.
Use jQuery’s Ajax method to send FormData data
//记录当前时间 var time=new Date().getTime(); //记录当前进度 var percentage =null; //记录当前上传速度 var velocity=null; //记录已上传文件字节大小 var loaded=0; $.ajax({ url: 'Url', type: "POST", data: formData, contentType: false, // 必须 不设置内容类型 processData: false, // 必须 不处理数据 xhr: function xhr() { //获取原生的xhr对象 var xhr = $.ajaxSettings.xhr(); if (xhr.upload) { //添加 progress 事件监听 xhr.upload.addEventListener('progress', function (e) { var nowDate = new Date().getTime(); //每一秒刷新一次状态 if (nowDate - time >= 1000) { //已上传文件字节数/总字节数 percentage = parseInt(e.loaded / e.total * 100); //当前已传大小(字节数)-一秒前已传文件大小(字节数) velocity = (e.loaded - loaded) / 1024; if (percentage >= 99) { $(".hintText").html('服务端正在解析,请稍后'); } else { //修改上次记录时间及数据大小 time = nowDate; loaded = e.loaded; } } else { return; } }, false); } return xhr; }, success: function success(response) { //成功回调 }, error: function error(error) { //失败回调 } });
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
Ajax+Servlet to implement non-refresh drop-down linkage (with code)
How to use Ajax to asynchronously check whether the user name is duplicated
The above is the detailed content of FormData+Ajax upload progress monitoring (with code). For more information, please follow other related articles on the PHP Chinese website!