This article shares with you the method of making Ajax requests and uploading files using the FormData object. Friends in need can refer to it.
XMLHttpRequest Level2 adds a new interface - FormData. [ is mainly used to send form data, but can also be used independently to transmit keyed data. Compared with ordinary Ajax, it can upload binary files asynchronously】
Using the FormData object, you can use some key-value pairs to simulate a series of form controls through js, and you can also Submit the form asynchronously using the send() method of XMLHttpRequest.
First of all, in the previous "Parameter Passing Method for Front-end and Back-end Interaction", we talked about the traditional form submission method (form serialization), which is only suitable for passing general parameters. The file stream of the uploaded file cannot be serialized and delivered. Therefore, using FormData, you can easily combine it with ajax to upload files.
1. Before introducing the use of FormData to make Ajax requests and upload files, let’s first get to know FormData and its use:::::
W3C draft provides three options to obtain or modify Form Data:::
WAY1: Create an empty Form Data object, and then use append() to add it one by one Key-value pair
var oMyForm = new FormData(); // 创建一个空的FormData对象 oMyForm.append("userName","Coco"); // append()方法添加字段 oMyForm.append("accountNum",123456); // 数字123456立即被转换成字符串“123456” oMyForm.append("userFile",fileInputElement.files[0]);var oFileBody = "<a id="a"><b id="b">hey!</b></a>"; var oBlob = new Blob([oFileBody],{type:"text/html"}); // Blob对象包含的文件内容是oFileBody oMyForm.append("webmasterfile",oBlob); var oReq = new XMLHttpRequest(); oReq.open("POST"," .php"); oPeq.send(oMyForm); // 使用XMLHttpRequest的send()把数据发送出去
The values of "userFile" and "webmasterfile" above both contain a file; the
field The value can be a Blob object, File object or string. Other types will be automatically converted to strings - such as "accountNum" above.
WAY2: Take the form element object as a parameter and pass it into the FormData object
—— Pseudo code——
var new_FormData = new FormData( someFormElement );
Example:
var FormElement = document.getElementById("myFormElement");var oReq = new XMLHttpRequest(); oReq.open("POST"," .php"); oReq.send(new FormData(FormData));
You can also add new key-value pairs based on the existing form:
var FormElement = document.getElementById("myFormElement");var formData = new FormData(FormElement); formData.append("serialnumber",serialNumber++);var oReq = new XMLHttpRequest(); oReq.send(formData);
You can add some fixed fields that you don’t want users to edit in this way before sending.
WAY3: Use the getFormData method of the form object to generate
var formobj = document.getElementById("myFormElement"); var formdata = formobj.getFormData();
Use the FormData object, combined with native js, through Ajax implements asynchronous uploading of images. Of course, the principle of existing jquery batch upload plug-ins is to use FormData.
2. Use the FormData object to send binary files:::::
way1: Initialize FormData through the form form
1. There is a form element containing a file input box in html
stash the file !2. Asynchronously upload the file selected by the user
function sendForm(){ var oOutput = document.getElementById("Output"); var oData = new FormData(document.forms.nameItem("fileInfo")); oData.append("customField","This is some extra data"); var oReq = new XMLHttpRequest(); oReq.open("POST"," .php",true); oReq.onload = function(oEvent){ if(oReq.status == 200){ oOutput.innerHTML = "Uploaded!"; }else{ oOutput.innerHTML = "Error" + oReq.status + "occurred uploading your file!" } }; oReq.send(oData); }
WAY2: Add a File object or a Blob object directly to the FormData object without using the form form
var data = new FormData();var oFileBody = "<a id="a"><b id="b">hey!</b></a>";var oBlob = new Blob([oFileBody],{type:"text/html"}); data.append("myfile",oBlob);
If a field value in the FormData object is a Blob object, when sending an HTTP request, the value of the "content-Disposition" request representing the file name of the file contained in the Blob object is different in different browsers:
Firefox uses the fixed string "blob", while chrome uses a random string.
WAY3: Use Jquery to send FormData (relevant items must be set correctly)
var fd =new FormData(document.getElementById("fileinfo")); fd.append("customField","This is some extra data"); $.ajax({ url:" .php", type:"POST", data:fd, processData:false, // 告诉jquery不要处理发送的数据 contentType:false // 告诉jquery不要设置content-Type请求头});
3. Example
1. Use FromData to make Ajax requests and upload files
<form id="uploadForm"> 指定文件名:<input type="text" name="filename" value=""> 上传文件:<input type="file" name="file"> <input type="button" value="上传" onclick="doUpload()"></form>
function doUpload(){ var formData = new FormData($("#uploadForm")[0]); $.ajax({ url:" .php", type:"POST", data:formData, async:false, cache:false, contentType:false, processData:false, success:function(returndata){ alert(returndata); }, error:function(returndata){ alert("error:"+returndata); } }); }
2. Use FormData to submit forms and upload images
<form name="form" id="formData"> name:<input type="text" name="name"> gender:<input type="radio" name="gender" value="1"> male <input type="radio" name="gender" value="2"> female photo:<input type="file" name="photo" id="photo"> <input type="button" name="btn" value="submit" onclick="submit();"> </form><p id="result"></p>
function submit(){ var data = new FormData($("#formData")[0]); $.ajax({ url:" .php", type:"POST", data:data, dataType:"JSON", cache:false, processData:false, contentType:false }).done(function(ret){ if(ret["isSuccess"]){ var result = ""; result +="name=" + ret["name"] + "<br>"; result += "gender=" + ret["gender"] + "<br>"; result += "<img src='"+ret['photo']+"' style="max-width:90%"FormData object makes Ajax request and uploads files" >"; $("#result").html(result); // 提交成功后将表单数据显示在id="result"的p里面 }else{ alert("提交失败"); } }); return false; }
4. Browser compatibility
Chrome | Firefox(Gecko) | IE | Opera | Safari |
7 | 4.0(2.0) | 10 | 12 | 5 |
Related recommendations:
jQuery uses FormData to implement file uploading
Use FormData to upload files with Ajax
The above is the detailed content of FormData object makes Ajax request and uploads files. For more information, please follow other related articles on the PHP Chinese website!

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

Setting the httponly flag is crucial for session cookies because it can effectively prevent XSS attacks and protect user session information. Specifically, 1) the httponly flag prevents JavaScript from accessing cookies, 2) the flag can be set through setcookies and make_response in PHP and Flask, 3) Although it cannot be prevented from all attacks, it should be part of the overall security policy.

PHPsessionssolvetheproblemofmaintainingstateacrossmultipleHTTPrequestsbystoringdataontheserverandassociatingitwithauniquesessionID.1)Theystoredataserver-side,typicallyinfilesordatabases,anduseasessionIDstoredinacookietoretrievedata.2)Sessionsenhances

PHPsessionscanstorestrings,numbers,arrays,andobjects.1.Strings:textdatalikeusernames.2.Numbers:integersorfloatsforcounters.3.Arrays:listslikeshoppingcarts.4.Objects:complexstructuresthatareserialized.

TostartaPHPsession,usesession_start()atthescript'sbeginning.1)Placeitbeforeanyoutputtosetthesessioncookie.2)Usesessionsforuserdatalikeloginstatusorshoppingcarts.3)RegeneratesessionIDstopreventfixationattacks.4)Considerusingadatabaseforsessionstoragei

Session regeneration refers to generating a new session ID and invalidating the old ID when the user performs sensitive operations in case of session fixed attacks. The implementation steps include: 1. Detect sensitive operations, 2. Generate new session ID, 3. Destroy old session ID, 4. Update user-side session information.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

WebStorm Mac version
Useful JavaScript development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version
SublimeText3 Linux latest version
