項目中使用圖片上傳功能,要實現能夠原地上傳和修改,一直查找許多資料,結合資料和組件完成此功能,但願對後邊的人有幫助java
源碼:app
style部分this
<el-upload
action="#"
list-type="picture-card"
:limit="6"
:file-list="fileList"
:on-preview="handlePictureCardPreview"
:on-remove="handleRemove"
:before-upload="beforeImageUpload"
:http-request="uploadImage"
:auto-upload="true"
>
<i class="el-icon-plus"></i>
</el-upload>
<el-dialog :visible.sync="dialogVisible">
<img width="100%" :src="dialogImageUrl" alt />
</el-dialog>
javaScript部分
export default {
data(){
return {
dialogImageUrl: '' ",
dialogVisible: false,
fileList: [],
}
},
methods{
//圖片上傳以前
beforeImageUpload(file) {
console.log(file)
var testmsg=file.name.substring(file.name.lastIndexOf('.')+1)
const isJpg = testmsg === 'jpg' || testmsg === 'png'
if (!isJpg) {
this.$message.error('上傳圖片只能是 jpg 或 png 格式!')
return false
}
const isLt2M = file.size / 1024 / 1024 < 2
if (!isLt2M) {
this.$message.error('上傳圖片大小不能超過 2MB!')
return false
}
// return false // (返回false不會自動上傳)
},
handlePictureCardPreview(file) {
this.dialogImageUrl = file.url
this.dialogVisible = true
},
handleRemove(file, fileList) {
for(var i = 0; i < this.fileList.length; i++){
if(this.fileList[i].url === file.url){
deleteImageReport(this.fileList[i].id).then(res =>{
this.$message.success('刪除圖片成功')
})
this.fileList.splice(i, 1)
}
}
},
//上傳圖片
uploadImage(image){
console.log(image.file)
let report = this.currentUser.id
let params = new FormData()
params.append('image', image.file)
params.append('report', report)
uploadImageFiles(params).then(res => {
console.log(res)
let url = { url: res.data.image, id:res.data.id }
this.fileList.push(url)
this.$message.success('上傳成功')
}).catch(() =>{
this.$message('上傳失敗,請從新上傳')
})
},
}
}