Use element to Upload component Upload
1. HTML section
<el-form ref="ruleForm_1" :model="ruleForm_1" :rules="rules" label-width="120px" class="ruleForm_1">
<el-form-item label="Image" prop="attachments">
<el-upload
class="upload-demo"
:action="actionUrl"
:data="{type:'image'}"
:on-success="handleSuccess"
:before-upload="handleBeforeUpload"
:on-remove="handleRemove"
:limit="1"
:on-exceed="handleExceed"
:file-list="fileList"
accept=".jpg,.png,.jpeg"
>
</el-form-item>
</el-form>
Copy the code
1.1. Attribute analysis
This parameter is mandatory. Action: Upload address Data: On-success: an on-success event, which can be placed here to handle interface parameters before-upload: an on-remove event, which can be corrected here on-remove: an on-remove event limit, which can be uploaded on-exceed: Accept: Filters files in the corresponding format. For example, if you upload pictures, only folders and image files will be displayed in the window
- Of course, there are other commonly used attributes that are not used (more on the EL website). Such as:
Show-file-list: specifies whether to display a list of uploaded files. Boolean headers: Specifies the headers of the upload request. If a token is required, list-type is used. The type of the file list. The default value is text, and the optional values are text/picture/picture-card. The following figure
- Default value: text
- picture
- picture-card
2. Js part
export default {
data() {
return {
actionUrl: process.env.VUE_APP_BASE_API + '/file/upload'.// Upload the component action address
fileList: [].// For data binding
ruleForm_1: { // For data requests
attachments: []}}},methods: {
// Delete the uploaded image
handleRemove(file, fileList) {
const index = this.fileList.findIndex(item= > item.uid === file.uid)
this.fileList = fileList
this.ruleForm_1.attachments.splice(index, 1)},// Upload success event (for data request)
handleSuccess(res, file, fileList) { // Upload succeeded
this.ruleForm_1.attachments.push({
name: res.data.name,
url: res.data.netResourcePath,
path: res.data.path,
size: res.data.size
})
},
// A hook for images that exceed the limit
handleExceed(files, fileList) {
this.$message.warning('Upload a maximum of 1 picture')},// Upload the image before the event, verification
handleBeforeUpload(file) {
const imgReg = /\.(jpg|png|jpeg)$/
const isLt1M = file.size / 1024 / 1024 < 2
if(! imgReg.test(file.name)) {this.$message.error('Upload images in JPG/PNG/JPEG format only! ')}if(! isLt1M) {this.$message.error('Upload image file size cannot exceed 2MB! ')}return imgReg.test(file.name) && isLt1M
},
}
}
Copy the code