在项目中需要上传大量的照片文件,照片文件中有拍摄位置、拍摄时间需要抓取出来做展示标记使用。同时对照片进行压缩,控制在200万象属即可。后台文件上传上采用MultipartFile类型文件最终上传到OSS服务器。
一、文件上传el-upload组件
采用是文件先选取,然后再上传的方式。
<el-upload
action="#"
:before-upload="beforeUpload"
:http-request="modeUpload"
:file-list="fileList"
accept="image/jpeg,image/jpg,image/tiff">
<el-button slot="trigger" size="small">
文件选取
<i class="el-icon-upload el-icon--right"></i>
</el-button>
<el-button style="margin-left: 10px;" size="small" type="success" @click="uploadImages">文件上传</el-button>
</el-upload>
二、文件上传前处理
上传前对文件大小、格式进行检查,只处理10M以下的图片,避免前端服务器负担。由于文件是按景区组织的,文件选取进行了需要先选择景区,否则文件传到OSS后没有对应的景区信息。
beforeUpload(file) {
const isImage = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/tiff'
const isLt10M = file.size / 1024 / 1024 < 10
const hasId = this.form.scenicId !== null && this.form.scenicId !== undefined
if (this.form.scenicId === null || this.form.scenicId === undefined) {
this.$message.error('请先选择景区后上传文件!')
}
if (!isImage) {
this.$message.error('上传文件只能是图片格式!')
}
if (!isLt10M) {
this.$message.error('上传文件大小不能超过 10MB!')
}
return hasId && isImage && isLt10M
},
//上传文件前,对文件进行赋值处理
modeUpload(item) {
this.file = item.file
},
三、文件上传
文件上传先提取EXIF信息,然后将文件读到Canvas进行压缩,产生的文件是URL数据,不能直接上传,上传前需要转换为file。
uploadImages() {
if (this.form.scenicId === null || this.form.scenicId === undefined) {
this.$message.error('请先选择景区后上传文件!')
return }
// 看支持不支持FileReader
if (!this.file || !window.FileReader) return
//进行对象转换,以便获取父组数据
let self =