vue界面和springboot后端分段传文件代码
时间: 2024-03-19 14:45:23 浏览: 179
springboot+vue前后端分离 实现超大文件分块上传
以下是一个简单的Vue界面和Spring Boot后端分段传输文件的代码示例:
Vue界面代码:
```
<template>
<div>
<input type="file" @change="selectFile">
<button @click="uploadFile">上传文件</button>
</div>
</template>
<script>
export default {
data() {
return {
file: null,
fileSize: 0,
chunkSize: 1024 * 1024, // 每个分段大小为1MB
chunks: [],
uploadedChunks: []
}
},
methods: {
selectFile(event) {
this.file = event.target.files[0]
this.fileSize = this.file.size
this.chunks = this.splitFileIntoChunks()
this.uploadedChunks = []
},
splitFileIntoChunks() {
const chunks = []
let chunkIndex = 0
let offset = 0
while (offset < this.fileSize) {
const chunk = this.file.slice(offset, offset + this.chunkSize)
chunks.push({
index: chunkIndex,
file: chunk,
uploaded: false
})
offset += this.chunkSize
chunkIndex++
}
return chunks
},
async uploadFile() {
for (let i = 0; i < this.chunks.length; i++) {
const chunk = this.chunks[i]
if (!chunk.uploaded) {
await this.uploadChunk(chunk)
}
}
},
uploadChunk(chunk) {
return new Promise((resolve, reject) => {
const formData = new FormData()
formData.append('file', chunk.file)
formData.append('index', chunk.index)
formData.append('total', this.chunks.length)
const xhr = new XMLHttpRequest()
xhr.open('POST', 'http://localhost:8080/upload')
xhr.setRequestHeader('Content-Type', 'multipart/form-data')
xhr.onload = () => {
if (xhr.status === 200) {
chunk.uploaded = true
this.uploadedChunks.push(chunk)
resolve()
} else {
reject()
}
}
xhr.onerror = () => {
reject()
}
xhr.send(formData)
})
}
}
}
</script>
```
Spring Boot后端代码:
```
@RestController
public class FileController {
private static final Logger logger = LoggerFactory.getLogger(FileController.class);
@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file,
@RequestParam("index") int index,
@RequestParam("total") int total) {
try {
// 检查上传的文件是否为空
if (file.isEmpty()) {
return ResponseEntity.badRequest().body("上传的文件不能为空");
}
// 创建目录
File uploadDir = new File("upload");
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
// 保存分段文件
File chunkFile = new File(uploadDir, index + ".part");
file.transferTo(chunkFile);
// 检查所有分段文件是否都已上传
if (index == total - 1) {
File outputFile = new File(uploadDir, file.getOriginalFilename());
FileOutputStream outputStream = new FileOutputStream(outputFile);
for (int i = 0; i < total; i++) {
File partFile = new File(uploadDir, i + ".part");
FileInputStream inputStream = new FileInputStream(partFile);
IOUtils.copy(inputStream, outputStream);
inputStream.close();
partFile.delete();
}
outputStream.close();
logger.info("文件 {} 上传成功", file.getOriginalFilename());
}
return ResponseEntity.ok().build();
} catch (IOException e) {
logger.error("文件上传失败", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件上传失败");
}
}
}
```
以上代码仅供参考,具体实现还需要根据您的实际需求进行调整。
阅读全文