1. 项目背景与需求分析
1.1 项目背景
1.2 需求分析
- 批量选择图片:用户应能够一次性选择多张图片进行上传。
- 图片预览:在图片上传前,用户应能够预览所选图片。
- 图片格式与大小限制:对上传的图片格式和大小进行限制,确保上传的图片符合要求。
- 上传进度显示:在上传过程中,用户应能够实时查看上传进度。
- 错误处理:对上传过程中可能出现的错误进行提示和处理。
2. Vue 实现批量图片处理与上传
2.1 项目搭建
首先,我们需要创建一个 Vue 项目。可以使用 Vue CLI 或 Vite 等工具快速搭建项目。
vue create batch-upload-project
cd batch-upload-project
npm run serve
2.2 引入 Element Plus
为了方便实现文件上传组件,我们将引入 Element Plus UI 组件库。
npm install element-plus --save
2.3 创建文件上传组件
<template>
<div class="batch-upload">
<el-upload
class="upload-demo"
action="https://jsonplaceholder.typicode.com/posts/"
:on-preview="handlePreview"
:on-remove="handleRemove"
:before-upload="beforeUpload"
:file-list="fileList"
multiple
:limit="maxFiles"
:on-exceed="handleExceed"
>
<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
</div>
</template>
<script>
export default {
data() {
return {
fileList: [],
maxFiles: 5,
};
},
methods: {
handlePreview(file) {
console.log(file);
},
handleRemove(file, fileList) {
console.log(file, fileList);
},
beforeUpload(file) {
const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png';
if (!isJPGorPNG) {
this.$message.error('上传图片只能是 JPG 或 PNG 格式!');
return false;
}
const isLt500KB = file.size / 1024 / 1024 < 0.5;
if (!isLt500KB) {
this.$message.error('上传图片大小不能超过 500KB!');
return false;
}
return isJPGorPNG && isLt500KB;
},
handleExceed(files, fileList) {
this.$message.warning(`最多只能上传 ${this.maxFiles} 张图片!`);
},
},
};
</script>
<style scoped>
.batch-upload {
margin: 20px;
}
</style>
2.4 使用文件上传组件
在父组件中引入并使用 BatchUpload.vue
组件。
<template>
<div>
<batch-upload></batch-upload>
</div>
</template>
<script>
import BatchUpload from './components/BatchUpload.vue';
export default {
components: {
BatchUpload,
},
};
</script>