This is the 132nd original article without water, if you want to get more original good articles, please search the public account to follow us. This article was first published in the front blog of political research cloud: Analysis of FormData
Before because of
In daily development, we used request encapsulated inside the company and did not pay much attention to the type of request parameters. From a common demand, the server proposed: The content-Type field of the previous Request Headers is application/ JSON, which is different from the server decoding rules. See the article “How SpringBoot Parsed Parameters”. I need to change it to multipart/form-data. After the change, the problem will be solved. By the way, I will summarize.
RESTful Introduction
The commonly used Internet software architecture RESTful has some rules and constraints, such as: Protocol, domain name, version, path, HTTP verb, status code, etc., this paper mainly summarizes part of THE CONTENT of HTTP verbs, that is, HTTP request methods, we commonly use GET, POST, PUT, etc. GET request should be familiar with, generally used to obtain resources. The client sends parameters through the URL. However, due to the length limitation of the URL, it can be used when the parameters are relatively small, such as some simple list pages. POST is a bit more complicated. It is generally used to submit data, and the client sends parameters through Request Body. This Request method is widely used in actual business scenarios (especially in middle and background systems).
The introduction ofFormData
In many cases, application/ JSON, Application/X-www-form-urlencoded and other types are often used in post data submission, which can cover most of the scenes, but there are some scenes, such as file upload, The content-type field in the request header, application/json, tells the server that the parameter is a serialized JSON string, so json.stringify is usually used to serialize the parameter. The json. stringify API is well supported by browsers, but json. stringify has problems converting certain data structures. Function arguments will be lost, circular references will fail, Blob /File objects will be converted to {}, etc. See why json. stringify is not recommended for deep copy. If you are interested, you can learn about it. This is the first one. Secondly, some students have said that if you want to upload pictures, you can convert them into Base64 format for uploading. The other thing is that the server receives this parameter and has to parse it, which is a hassle. At this point, FormData is available.
define
FormData is a type that is specifically tailored for forms. FormData is a type that provides a key/value pair for FormData. For example, if you need to upload a file, you can use FormData to upload a file. Windows also mount FormData directly, which is very convenient for you to use directly.
We instantiate a FormData object on the console and print it as follows
use
If you look carefully, you can see that there are set, GET, values, has and other methods. The main use of our development is the Append method, which usually encapsulates a layer of request. The calling layer only needs to pass in the object collection of the parameters.
const specialFileType = ['Blob'.'File'];
function formatData (_data) {
const data = new window.FormData()
for (const key in _data) {
let value = _data[key]
if (_data[key] instanceof Object && !specialFileType.includes(_data[key].constructor.name)) {
value = JSON.stringify(_data[key])
}
data.append(key, value)
}
return data
}
Copy the code
append
or set
If the append key exists, it will append to the set of existing values, and the set will overwrite the existing values with new values, so which one to use depends on your needs.
FormData has an advantage in uploading files. How does it handle this? The FormData object can set three types of values: string, Blob, and File, so we don’t need to convert them. We can just pass the File. When we pass the File to the formatData layer, it will be appended directly into the FormData object. The type of d and e parameters is binary, so the server can easily obtain the value after receiving it.
cosnt View = () = > {
const [fileA, setFileA] = useState(null);
const [fileB, setFileB] = useState(null);
const handleClick = () = > {
console.log('fileA:', fileA)
console.log('fileB:', fileB)
const p = {
a: { a1: 11.a2: 22 },
b: [1.2.3].c: 123.d: fileA[0].e: fileB[0],}const data = formatData(p);
axios({
method: 'POST'.url: '/aa',
data,
// headers: {
// 'content-type': 'multipart/formdata'
// },})}return <div>
<div onClick={handleClick}>Send the request</div>
<input
type='file'
onChange={(a)= >{ const v = a.target.files; setFileA(v); }} / ><input
type='file'
onChange={(a)= >{ const v = a.target.files; setFileB(v); }} / ></div>
}
Copy the code
You can see that each parameter is separated by a ——WebKitFormBoundary ***, which is actually the FormData specification flag, and the string behind it is created automatically by the browser for us, ——WebKitFormBoundary *** is used as a separator, also as a beginning and an end, and its contents mainly include content-disposition, content-Type, etc. Content-disposition is mandatory. The name attribute represents the key of the form element, filename is the name of the uploaded file, and can also be changed using the third parameter FormData. Additionally, I did not change the content-Type in the request header when I sent the request. If the content-type of the request header is set to an object, some browsers will automatically add the content-type to the request header for us: Text /plain, if the data is FormData, will automatically add content-type: Multipart /form-data, etc., may behave differently in different browsers, but the best way is for the client and the server to agree on a content-type, fixed delivery.
conclusion
In our daily development, the existing several can meet our use requirements, but there may be some deviation in some special scenarios. The specific use depends on the scenario and the agreement with the server. The agreement is better than the configuration.
Reference article:
www.ruanyifeng.com/blog/2011/0…
zhuanlan.zhihu.com/p/122912935
Juejin. Cn/post / 688572…
Recommended reading
Why is index not recommended as key in Vue
Brief analysis of Web screen recording technology scheme and implementation
Open source works
- Political cloud front-end tabloid
Open source address www.zoo.team/openweekly/ (wechat communication group on the official website of tabloid)
- Item selection SKU plug-in
Open source addressGithub.com/zcy-inc/sku…
, recruiting
ZooTeam, a young passionate and creative front-end team, belongs to the PRODUCT R&D department of ZooTeam, based in picturesque Hangzhou. The team now has more than 60 front-end partners, with an average age of 27, and nearly 40% of them are full-stack engineers, no problem in the youth storm group. The members consist of “old” soldiers from Alibaba and NetEase, as well as fresh graduates from Zhejiang University, University of Science and Technology of China, Hangzhou Electric And other universities. In addition to daily business docking, the team also carried out technical exploration and practice in material system, engineering platform, building platform, performance experience, cloud application, data analysis and visualization, promoted and implemented a series of internal technical products, and continued to explore the new boundary of front-end technology system.
If you want to change what’s been bothering you, you want to start bothering you. If you want to change, you’ve been told you need more ideas, but you don’t have a solution. If you want change, you have the power to make it happen, but you don’t need it. If you want to change what you want to accomplish, you need a team to support you, but you don’t have the position to lead people. If you want to change the pace, it will be “5 years and 3 years of experience”; If you want to change the original savvy is good, but there is always a layer of fuzzy window… If you believe in the power of believing, believing that ordinary people can achieve extraordinary things, believing that you can meet a better version of yourself. If you want to be a part of the process of growing a front end team with deep business understanding, sound technology systems, technology value creation, and impact spillover as your business takes off, I think we should talk. Any time, waiting for you to write something and send it to [email protected]