Implementing a Universal File Upload Interface with Vue.js
Building a Frontend File Upload Componnet
This implementation creates a reusable file upload interface that can be integrated across different components. The solution uses Vue.js with Element Plus components for the UI.
Avatar Selection Component
The avatar selector combines an image display with a drawer component containing the upload functionality:
<template>
<el-avatar
:size="60"
:src="currentAvatar"
@click="showUploadDrawer"
class="clickable-avatar">
<img src="https://example.com/default-avatar.png" />
</el-avatar>
<el-drawer v-model="uploadVisible" title="Image Upload" size="600px">
<file-uploader @file-changed="handleFileChange" />
</el-drawer>
</template>
Reusable Upload Component
The core upload component handles file selection:
<template>
<el-upload
class="image-uploader"
:show-file-list="false"
:on-change="processFile">
<el-icon class="upload-icon">
<Plus />
</el-icon>
</el-upload>
</template>
Backend Implementation
The server-side processing involves these key steps:
- Controller Layer:
@PostMapping("/upload")
public ResponseEntity<String> handleUpload(@RequestBody FileUploadRequest request) {
String fileUrl = fileService.processUpload(request);
return ResponseEntity.ok(fileUrl);
}
- Service Layer:
public String processUpload(FileUploadRequest request) {
// Generate unique filename
String uniqueName = IdUtil.fastUUID() + "_" + PinyinUtil.getPinyin(request.getOriginalName());
// Process base64 data
String encodedData = StrUtil.subAfter(request.getBase64Data(), ",", false);
byte[] fileBytes = Base64.getDecoder().decode(encodedData);
// Save file and return URL
return fileStorage.saveFile(uniqueName, fileBytes);
}
The implementation supports various file types by proper handling base64 encoding and includes cloud storage integration capabilities.