Java后端(Spring Boot)和Vue前端(ElementUI的el-upload、vue-simple-uploader)实现大文件分片断点续传上传并有进度条显示上传情况
在Spring Boot后端,你需要创建一个控制器来处理文件上传的HTTP POST请求。以下是一个简单的例子:
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@RestController
public class FileUploadController {
private static final String UPLOAD_DIR = "/path/to/upload/dir";
@PostMapping("/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return "File is empty";
}
try {
byte[] bytes = file.getBytes();
Path path = Paths.get(UPLOAD_DIR + File.separator + file.getOriginalFilename());
Files.write(path, bytes);
return "File uploaded successfully: " + file.getOriginalFilename();
} catch (IOException e) {
e.printStackTrace();
return "File upload failed: " + e.getMessage();
}
}
}
在Vue前端,你可以使用ElementUI的el-upload
组件或者vue-simple-uploader
来上传文件。以下是使用el-upload
组件的例子:
<template>
<el-upload
action="http://localhost:8080/upload"
:on-success="handleSuccess"
:on-error="handleError">
<el-button slot="trigger" size="small" type="primary">选择文件</el-button>
<el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
</el-upload>
</template>
<script>
export default {
methods: {
handleSuccess(response, file, fileList) {
console.log('File uploaded successfully:', response);
},
handleError(err, file, fileList) {
console.error('Error during upload:', err);
},
submitUpload() {
this.$refs.upload.submit();
}
}
}
</script>
确保你的Vue项目已经配置了正确的后端URL,并且有正确的跨域请求设置(如果前端和后端不在同一个域上)。这样就可以实现文件从Vue前端到Spring Boot后端的上传功能。
评论已关闭