The front end implements base64 encoding processing

When the file is uploaded, the backend fails to receive it because the base64 file string is too long.



foreword

提示:以下是本篇文章正文内容,下面案例可供参考

1. What is base64 encoding?

Base64 is an encoding method for converting binary data into printable characters in the ASCII character set. It is often used to transfer binary data between different systems, since many systems only support the transfer of text data.

2. Implementation steps

1. Read the file to be uploaded into memory, and use FileReader to convert it into a Base64-encoded string:

The code is as follows (example):

const reader = new FileReader()
	reader.readAsDataURL(file) // 读取文件并转换成 Base64 编码
	reader.onload = (event) => {
    
    
	  const base64String = event.target.result
	  // ...
}

2. Chunk the Base64-encoded string. Because when uploading a large file, directly uploading the Base64 encoding of the entire file as a string may cause the browser to crash or the upload to fail. Therefore, we need to split the Base64 encoded string into multiple smaller chunks for upload

The code is as follows (example):

const CHUNK_SIZE = 1024 * 1024 // 每个块的大小为 1MB
const chunks = []
let start = 0
let end = CHUNK_SIZE
while (start < base64String.length) {
    
    
  chunks.push(base64String.slice(start, end))
  start = end
  end += CHUNK_SIZE
}

The data requested by the url network used here.


3. Upload the chunked data. We can use axios or other HTTP library to upload data. As each chunk is uploaded, we need to put it into FormData and upload it as the body part of the HTTP request.

The code is as follows (example):

const formData = new FormData()
formData.append('file', chunk)
axios.post('/upload', formData)

The data requested by the url network used here.


4. After the upload is complete, merge all the chunked data into a complete file on the server side. The specific implementation method may vary according to the language and framework of the server side.

The code is as follows (example):

const reader = new FileReader()
reader.readAsDataURL(file) // 读取文件并转换成 Base64 编码
reader.onload = (event) => {
    
    
  const base64String = event.target.result
  const CHUNK_SIZE = 1024 * 1024 // 每个块的大小为 1MB
  const chunks = []
  let start = 0
  let end = CHUNK_SIZE
  while (start < base64String.length) {
    
    
    chunks.push(base64String.slice(start, end))
    start = end
    end += CHUNK_SIZE
  }
  let completedChunks = 0
  chunks.forEach((chunk) => {
    
    
    const formData = new FormData()
    formData.append('file', chunk)
    axios.post('/upload', formData)
      .then(() => {
    
    
        completedChunks++
        if (completedChunks === chunks.length) {
    
    
          // 所有分块上传完成,通知服务器合并文件
          axios.post('/merge', {
    
     filename: file.name })
        }
      })
      .catch((error) => {
    
    
        console.error(error)
      })
  })
}

The above is the detailed code for block upload in base64 data format (front-end processing)


Summarize

提示:这里对文章进行总结:

For example: the above is the processing flow of base64 encoding. There are still many methods on the Internet, including native API methods. Some of them may be abandoned due to compatibility issues. Of course, there are some performance-related solutions, such as webworker.

Guess you like

Origin blog.csdn.net/weixin_48211022/article/details/129733383