Java如何实现文件分片上传的?

摘要:文件分片上传 核心思想:前端分片上传,后端合并文件 测试页面 <!doctype html> <html lang="en&quot
文件分片上传 核心思想:前端分片上传,后端合并文件 测试页面 <!doctype html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>文件分片上传</title> </head> <body> <input type="file" id="fileInput" /> <button onclick="uploadFile()">上传</button> <script> function uploadFile() { const fileInput = document.getElementById('fileInput') const file = fileInput.files[0] if (!file) { alert('请选择文件') return } const chunkSize = 1024 * 1024 // 每个分片 1MB const totalChunks = Math.ceil(file.size / chunkSize) const identifier = file.name + '_' + file.size let currentChunk = 0 function uploadChunk() { const start = currentChunk * chunkSize const end = Math.min(start + chunkSize, file.size) const chunk = file.slice(start, end) const formData = new FormData() formData.append('file', chunk) formData.append('chunkNumber', currentChunk) formData.append('totalChunks', totalChunks) formData.append('identifier', identifier) const xhr = new XMLHttpRequest() xhr.open('POST', 'http://localhost:8080/file/uploadChunk', true) xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status === 200) { const response = JSON.parse(xhr.responseText) if (response.success) { currentChunk++ if (currentChunk < totalChunks) { uploadChunk() } else { mergeChunks() } } else { alert('分片上传失败: ' + response.message) } } else { alert('请求出错: ' + xhr.status) } } } xhr.send(formData) } function mergeChunks() {
阅读全文