Ajax learning-FormData object

1. The role of the FormData object

  • Simulating HTML forms is equivalent to mapping HTML forms into form objects, automatically splicing the data in the form objects into the format of request parameters
  • Upload binary files asynchronously

2. Use of FormData Object

  • 1. Prepare the html form
<form id="form">
     <input type="text" name="username" />
     <input type="password" name="password" />
     <input type="button"/>
</form>
  • 2. Convert the HTML form into a formData object
var form = document.getElementById('form'); 
var formData = new FormData(form);
  • 3. Submit the form object
xhr.send(formData);

Note:
1. The Formdata object cannot be used for get requests, because the object needs to be passed to the send method, and the request parameters of the get request method can only be placed after the request address.
2. The server-side bodyParser module cannot parse the form data of the formData object, we need to use the formidable module to parse.

  • Demo
    server-side code
// 引入express框架
const express = require('express');
// 路径处理模块
const path = require('path');
const formidable = require('formidable');
// 创建web服务器
const app = express();
app.post('/formData', (req, res) => {
    
    
	// 创建formidable表单解析对象
	const form = new formidable.IncomingForm();
	// 解析客户端传递过来的FormData对象
	form.parse(req, (err, fields, files) => {
    
    
		res.send(fields);
	});
});
// 监听端口
app.listen(3000);
// 控制台提示输出
console.log('服务器启动成功');

Client code

<body>
	//准备 HTML 表单
    <form action="" id="form">
        <input type="text" name="usernam">
        <input type="password" name="password">
        <input type="button" name="" id="btn" value="提交">
    </form>
    <script>
        var btn = document.getElementById('btn');
        var form = document.getElementById('form');
        //添加点击事件
        btn.onclick = function () {
    
    
        	//将 HTML 表单转化为 formData 对象
            var formData = new FormData(form);
            var xhr = new XMLHttpRequest();
            xhr.open('post','http://localhost:3000/formData');
            //提交表单对象
            xhr.send(formData);
            xhr.onload = function () {
    
    
                if(xhr.status = 200){
    
    
                    console.log(xhr.responseText);
                }
              }
        }
    </script>
</body>

Print the result after submitting the form
Insert picture description here

3. Instance method of FormData object

There are many instance methods of the FormData object. You can see its instance objects in the console output formData object. Here are four commonly used ones

Insert picture description here

  • 1. Get the value of the attribute in the form object
formData.get('key');
  • 2. Set the value of the attribute in the form object
formData.set('key', 'value');
  • 3. Delete the value of the attribute in the form object
formData.delete('key');
  • 4. Append attribute values ​​to form objects
formData.append('key', 'value');

Note: The difference between the set method and the append method is that when the attribute name already exists, set will overwrite the value of the existing key name, and append will retain two values.

4. FormData binary file upload

  • Binary file upload client core code
			<input type="file" id="file"/>
             var file = document.getElementById('file')
            // 当用户选择文件的时候
             file.onchange = function () {
    
    
                 // 创建空表单对象
                 var formData = new FormData();
                 // 将用户选择的二进制文件追加到表单对象中
                 formData.append('attrName', this.files[0]);
                 // 配置ajax对象,请求方式必须为post
                 xhr.open('post', 'www.example.com');
                 xhr.send(formData);
             }
  • FormData file upload progress display
             // 当用户选择文件的时候
             file.onchange = function () {
    
    
                 // 文件上传过程中持续触发onprogress事件
                 xhr.upload.onprogress = function (ev) {
    
    
                     // 当前上传文件大小/文件总大小 再将结果转换为百分数
                     // 将结果赋值给进度条的宽度属性 
                     bar.style.width = (ev.loaded / ev.total) * 100 + '%';
                 }
             }
  • FormData file upload image instant preview

After we upload the image to the server, the server usually passes the image address as the response data to the client. The client can obtain the image address from the response data, and then display the image on the page.

				xhr.onload = function () {
    
    
                     var result = JSON.parse(xhr.responseText);
                     var img = document.createElement('img');
                     img.src = result.src;
                     img.onload = function () {
    
    
                         document.body.appendChild(this);
                     }
                 }
  • Demo code
    Server-side code
// 实现文件上传的路由
app.post('/upload', (req, res) => {
    
    
	// 创建formidable表单解析对象
	const form = new formidable.IncomingForm();
	// 设置客户端上传文件的存储路径
	form.uploadDir = path.join(__dirname, 'public', 'uploads');
	// 保留上传文件的后缀名字
	form.keepExtensions = true;
	// 解析客户端传递过来的FormData对象
	form.parse(req, (err, fields, files) => {
    
    
		// 将客户端传递过来的文件地址响应到客户端
		res.send({
    
    
			path: files.attrName.path.split('public')[1]
		});
	});
});

Client code

<body>
	<div class="container">
		<div class="form-group">
			<label>请选择文件</label>
			<input type="file" id="file">
			<div class="padding" id="box">
				<!-- <img src="" alt="" class="img-rounded img-responsive"> -->
			</div>
			<div class="progress">
				<div class="progress-bar" style="width: 0%;" id="bar">0%</div>
			</div>
		</div>
	</div>
	<script>
		var file = document.getElementById('file');
		var bar = document.getElementById('bar');
		var box = document.getElementById('box');
		file.onchange = function(){
    
    
			var formData = new FormData();
			//将用户选择的文件追叫到formData表单对象中
			formData.append('attrName',this.files[0]);	

			var xhr = new XMLHttpRequest();
			xhr.open('post','http://localhost:3000/upload');
			//文件上传过程中持续触发
			xhr.upload.onprogress = function (ev) {
    
    
				//ev.loaded 文件上传了多少
				//ev.total 上传文件总大小
				var result = (ev.loaded / ev.total) * 100 + '%';
				bar.style.width = result;
				//将百分比显示子进度条中
				bar.innerHTML = result;
			  }
			xhr.send(formData);
			xhr.onload = function () {
    
    
				if(xhr.status == 200){
    
    	
					var result = JSON.parse(xhr.responseText);
					//动态创建img标签
					var img  = document.createElement('img');
					img.src = result.path;
					img.onload = function () {
    
    
						//图片加载完成后将图片显示在浏览器中
						box.appendChild(img);
					  }		
				}
			  }
		}
	</script>
</body>
  • Browser display page
    Insert picture description here

One last word: Happy 1024 to all programmers! ! !

Guess you like

Origin blog.csdn.net/dairen_j/article/details/109260523