当前位置:网站首页>How to use the input table one-way service to send (occupy less) picture files (body transmission)? FileReader built-in object involved
How to use the input table one-way service to send (occupy less) picture files (body transmission)? FileReader built-in object involved
2022-04-23 17:15:00 【MiMenge】
origin
There is a problem when writing data processing background ?input:file When sending files to the background, it is found that the files cannot be uploaded as a whole , After uploading, it cannot be written directly to the static file of the service
solve
1 Use input:file Receive files to upload
Note that the file encoding here needs to use
input.files[0]Come and get it , Ordinary passinput.valueOnly the file stream address can be obtained
<body>
<input type="file" name="" id="file">
<button class="btn"> Upload </button>
<script> document.getElementsByClassName('btn')[0].addEventListener('click', () => {
console.log(document.getElementById('file').value); // C:\fakepath\01.jpg }); </script>
</body>
Use
input:files, You can get a list of files
<body>
<input type="file" name="" id="file">
<button class="btn"> Upload </button>
<script> document.getElementsByClassName('btn')[0].addEventListener('click', () => {
console.log(document.getElementById('file').files); // FileList {0: File, length: 1} }); </script>
</body>
Get the file object to upload
<body>
<input type="file" name="" id="file">
<button class="btn"> Upload </button>
<script> document.getElementsByClassName('btn')[0].addEventListener('click', () => {
console.log(document.getElementById('file').files[0]); // File {name: '05.jpg', lastModified: 1646900166527, lastModifiedDate: Thu Mar 10 2022 16:16:06 GMT+0800 ( China standard time ), webkitRelativePath: '', size: 4201, …} // lastModified: 1646900166527 // lastModifiedDate: Thu Mar 10 2022 16:16:06 GMT+0800 ( China standard time ) {} // name: "05.jpg" // size: 4201 // type: "image/jpeg" // webkitRelativePath: "" }); </script>
</body>
2 We need to change the file data transcoding , Here will be converted to base64 A character
- A built-in object needs to be used in the process of conversion
FileReader
FileReader Object is used to asynchronously read the user's local file - attribute
| attribute | describe |
|---|---|
| error | Error reading file |
| readyState | Indicates the status of file reading . 0 Indicates that no data is loaded ; 1 Indicates that the data is being loaded ; 2 Indicates that all data has been loaded |
| result | Read the contents of the file |
- event
| event | describe |
|---|---|
| onabout | Triggered when reading interrupt |
| onerror | Triggered when the read fails |
| onload | Trigger after reading |
| onloadstart | Triggered at the start of the read |
| onloadend | Triggered at the end of the read , And load The difference is ,loadend It will be triggered when it succeeds or fails |
| onprogress | File read Blob Trigger when |
- Method
| Method | describe |
|---|---|
| about() | Terminate read |
| readAsArrayBuffer() | Start reading the specified Blob The content in , Once that is done , result Properties will be saved in the read file ArrayBuffer Data objects |
| readAsDataURL() | Read Blob file ; The read file will appear as date:base64URL How to save |
| readAsText() | Read the specified Blob The content in . Once that is done ,result Property will contain a string to represent the contents of the file being read |
- It's mainly used here
readAsDataURL Method
transcoding
<body>
<input type="file" name="" id="file">
<button class="btn"> Upload </button>
<script>
document.getElementsByClassName('btn')[0].addEventListener('click', () => {
let file = document.getElementById('file').files[0];
// Create read instance
let readFile = new FileReader();
// Start reading
readFile.readAsDataURL(file);
// Listen and read status
readFile.addEventListener('load', () => {
// After reading, get base64 Bit initial data
let base64 = readFile.result;
console.log(base64);
// data:image/jpeg;base64,/9j/4AAQSkZJRg················IgIiICIiAiIgf/2Q==
// complete Of base Show at the end of the article
});
});
</script>
</body>
3 take base64 The string is sent to the server
Omit
Because it uses body transmission , Therefore, there is no need to configure the following header information
let header = new Headers({
‘Content-Type’: ‘multipart/form-data’,
});
4 Server receive base64 And deal with
To use the node Service as an example
// Interface for uploading picture data
dataRouter.post('/summit', (request, response) => {
// obtain body In the parameter base64 character
let {
base64Data } = request.body;
// Filter data:URL --- Replace with regular base64 The picture in front of the character marks the information
let base64Data = address.replace(/^data:image\/\w+;base64,/, "");
});
utilize Buffer To buffer data
The server will write the specified received picture to the service , It needs to be transformed into buffer data
dataRouter.post('/summit', (request, response) => {
// obtain body In the parameter base64 character
let {
base64Data } = request.body;
// Filter data:URL --- Replace with regular base64 The picture in front of the character marks the information
let base64Data = address.replace(/^data:image\/\w+;base64,/, "");
// To buffer
let buffer = new Buffer.from(base64Data, 'base64');
// Write service
fs.writeFile('xxxx/xxx', buffer, (···) => {
···});
});
This involves Buffer, You can see link
In this way, you can upload pictures to the server
版权声明
本文为[MiMenge]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230553027587.html
边栏推荐
- Generate random numbers with high quality and Gaussian distribution
- Clickhouse table engine
- Promise (I)
- Signalr can actively send data from the server to the client
- Further study of data visualization
- Milvus 2.0 质量保障系统详解
- AIOT产业技术全景结构-数字化架构设计(8)
- Seven cattle upload pictures (foreground JS + background C API get token)
- Further optimize Baidu map data visualization
- Freecodecamp ---- budget & category exercise
猜你喜欢

VLAN advanced technology, VLAN aggregation, super VLAN, sub VLAN
![[WPF binding 3] listview basic binding and data template binding](/img/2e/fbdb4175297bb4964a8ccfd0b909ae.png)
[WPF binding 3] listview basic binding and data template binding

. net type transfer

JS, entries(), keys(), values(), some(), object Assign() traversal array usage

Further study of data visualization

Shell script -- shell programming specification and variables

Devexpress GridView add select all columns
![[logical fallacy in life] Scarecrow fallacy and inability to refute are not proof](/img/71/14a17128dbe0f02edb4db3da479ef2.jpg)
[logical fallacy in life] Scarecrow fallacy and inability to refute are not proof
![[registration] tf54: engineer growth map and excellent R & D organization building](/img/12/7aece45fbc9643c97cdda94b405118.jpg)
[registration] tf54: engineer growth map and excellent R & D organization building

Feign report 400 processing
随机推荐
El date picker limits the selection range from the current time to two months ago
MySQL master-slave configuration under CentOS
VLAN高级技术,VLAN聚合,超级Super VLAN ,Sub VLAN
Understanding and small examples of unity3d object pool
RPC核心概念理解
Promise (I)
Rtklib 2.4.3 source code Notes
Signalr can actively send data from the server to the client
freeCodeCamp----prob_ Calculator exercise
线性代数感悟之1
Self use learning notes - connectingstring configuration
Variable length parameter__ VA_ ARGS__ Macro definitions for and logging
oracle 中快速获取表的列名列表
ASP. NET CORE3. 1. Solution to login failure after identity registers users
Wiper component encapsulation
Deep understanding of control inversion and dependency injection
[C] thoroughly understand the deep copy
JS, entries(), keys(), values(), some(), object Assign() traversal array usage
Further study of data visualization
Understanding of RPC core concepts