后台上传:Java+Vue+Websocket实现OSS文件上传进度条功能完整教程
// Java后端代码,使用Spring Boot和Spring Security
@Controller
@RequestMapping("/api/oss")
public class OssUploadController {
@Autowired
private OssService ossService;
@MessageMapping("/upload")
@SendTo("/topic/upload")
public UploadStatus uploadStatus(UploadStatus status) {
return status;
}
@PostMapping("/multipart")
public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file,
@RequestParam("folder") String folder,
HttpSession session) {
String username = SecurityContextHolder.getContext().getAuthentication().getName();
ossService.uploadFileToOSS(file, folder, username);
return ResponseEntity.ok("File upload started");
}
}
// Vue前端代码,使用axios和vue-socket.io
<template>
<div>
<input type="file" @change="uploadFile" />
<progress :value="progress" max="100">{{ progress }}%</progress>
</div>
</template>
<script>
import io from 'socket.io-client';
export default {
data() {
return {
socket: io('http://localhost:8080/'),
progress: 0
};
},
methods: {
uploadFile(event) {
const file = event.target.files[0];
const formData = new FormData();
formData.append('file', file);
formData.append('folder', 'myfolder');
this.socket.emit('upload', formData);
axios.post('/api/oss/multipart', formData, {
onUploadProgress: progressEvent => {
this.progress = parseInt(Math.round((progressEvent.loaded * 100) / progressEvent.total));
}
});
}
},
sockets: {
connect() {
console.log('Socket connected');
},
upload(status) {
this.progress = status.progress;
}
}
};
</script>
这个示例展示了如何使用Java Spring Boot和Spring Security进行OSS文件上传,以及如何使用Vue.js和vue-socket.io实现前端的Websocket进度条功能。代码中包含了文件上传的接口定义和实现,以及进度条的更新逻辑。
评论已关闭