Project scenario:
Recently, I encountered a place where files need to be uploaded in the project. It is the first time to use it. This is a record of learning. If there is anything wrong, please correct me.
describe:
For the method name and attributes of el-upload, please refer to the official document of element, here are only some of the ones I useThe style I use is drag and drop upload
code show as below:
<el-upload
ref="myUpload" 上传文件的名字
name="file"
class="upload-demo"
drag 允许拖拽(不写默认false)
action="/XXXXXXX" 上传的地址
accept=".xls,.XLS,.xlsx,.XLSX,.csv,.CSV" 允许上传的文件格式,可以自定义
multiple="false" 是否支持多选文件
limit="1" 允许上传的文件个数(此处可结合上一个属性)
:auto-upload="false" 是否自动上传(此处为了效果选择false)
:on-exceed="handleExceed" 文件超出个数限制时的钩子(可在此设置提示)
:on-success="handleSuccess" 文件上传成功时的钩子
:on-error="handleError" 文件上传失败时的钩子
:data="ruleForm" 上传时附带的额外参数
>
<i class="el-icon-upload"></i>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
<div class="el-upload__tip" slot="tip">只能上传xls,xlsx,csv文件</div>
</el-upload>
It should be noted that the file upload method is form upload, so the format of the parameter is not JSON, but multipart/form-data
Here are some hook functions I used
//文件超出限制时
handleExceed() {
this.$message.warning('当前只允许选择 1 个文件!')
},
// 移除文件
clearFiles() {
this.$refs['myUpload'].clearFiles()
},
// 弹窗中的新增
employee() {
this.$refs['myUpload'].submit()
},
// 文件上传成功时
handleSuccess(res) {
this.$message.success('上传成功!')
// 可以写一些其他操作,例如刷新页面
},
// 文件上传失败时
handleError(res) {
this.$message.error('<错误的提示>')
}