当前位置:网站首页>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 pass input.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