vue-element-admin http-request自定义上传文件
需求是点击上传或者拖曳上传,http-request自定义上传,不自动上传,点击Apply之后再上传。以下是代码部分:
1.视图代码
<el-dialog
:title="upload.title"
:visible.sync="upload.open"
width="400px"
:destroy-on-close="true"
append-to-body
>
<el-upload
ref="upload"
class="upload-demo"
drag
action="customize"
accept=".torrent"
:limit="1"
:http-request="httpRequest"
:auto-upload="false"
>
<i class="el-icon-upload"></i>
<div class="el-upload__text">
Drag the file here, or
<em>Click upload</em>
</div>
<div class="el-upload__tip" slot="tip">Support extension: .torrent</div>
</el-upload>
<div slot="footer" class="dialog-footer">
<el-button type="primary" @click="submitFileForm">Apply</el-button>
<el-button @click="cancelFileForm">Cancel</el-button>
</div>
</el-dialog>
:destroy-on-close="true" 是el-dialog 关闭之后清空缓存
:auto-upload="false" 是否在选取文件后立即进行上传,为false,不立即上传
accept=".torrent" 是允许选择的文件类型
:http-request="httpRequest" 可以自定义上传的实现
action="customize" action 填空或者customize
2.script部分自定义上传文件方法
httpRequest(item) {
const isLt1M = item.file.size / 1024 / 1024 < 1
if (!isLt1M) {
this.msgError('Upload file size cannot exceed 1MB!')
}
if (isLt1M === true) {
let mf = new FormData()
mf.append('file', item.file)
uploadForDynamic(mf).then(res => {
if (res.code === 200) {
this.msgSuccess('Uploaded successfully')
this.upload.open = false
}
}).catch(err => {
console.log(err)
})
}
},
export function uploadForDynamic(data) {
return request({
url: '/net/uploadForDynamic',
method: 'post',
data: data
})
}
2.script部分上传按钮方法
视图部分一定要加上ref="upload"
,不然无法执行成功
submitFileForm() {
this.$refs.upload.submit()
}