当前位置:网站首页>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.value
Only 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
边栏推荐
- Preliminary understanding of promse
- Use of Shell sort command
- Shell脚本——Shell编程规范及变量
- . net type transfer
- Oninput one function to control multiple oninputs (take the contents of this input box as parameters) [very practical, very practical]
- Baidu Map Case - Zoom component, map scale component
- Variable length parameter__ VA_ ARGS__ Macro definitions for and logging
- El date picker limits the selection range from the current time to two months ago
- Shell - introduction, variables, and basic syntax
- Promise (I)
猜你喜欢
. net cross platform principle (Part I)
2. Electron's HelloWorld
VLAN高级技术,VLAN聚合,超级Super VLAN ,Sub VLAN
Using quartz under. Net core -- job attributes and exceptions of [4] jobs and triggers
Nacos + aspnetcore + Ocelot actual combat code
快时钟同步慢时钟域下的异步控制信号slow clk to fast clk
CentOS MySQL multi instance deployment
Go language, array, string, slice
Lock lock
JS, entries(), keys(), values(), some(), object Assign() traversal array usage
随机推荐
.Net Core3. 1 use razorengine NETCORE production entity generator (MVC web version)
[PROJECT] small hat takeout (8)
Using quartz under. Net core - [1] quick start
ClickHouse-表引擎
Conversion between hexadecimal numbers
[C#] 彻底搞明白深拷贝
MySQL modify master database
Self use learning notes - connectingstring configuration
Preliminary understanding of promse
Collect blog posts
Website_ Collection
1-3 components and modules
Perception of linear algebra 2
Further optimize Baidu map data visualization
CentOS MySQL multi instance deployment
1-4 configuration executable script of nodejs installation
C语言函数详解
Lock锁
First knowledge of go language
El cascade and El select click elsewhere to make the drop-down box disappear