在vue 项目里使用原生input的上传,前端展示图片,并且完成上传
--------------------------------------------------------------------------------------------
每次上传一个图片文件
<input type="file" id="file" @change="changeFile"/>
<img :src="uploadImg" alt="">
--------------------------------------------------------------------------------------------
changeFile() {
let file = document.querySelector("#file").files[0];
console.log(document.querySelector("#file").files);
let _uploadData = new FormData();
_uploadData.append("multipartFile", file); let that = this
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onloadstart = function () {
// axios 的上传函数
uploadFileApi(_formData).then(res => {})
};
//操作完成
reader.onload = function (e) {
//file 文件转为图片的格式
that.uploadImg = reader.result;
};
},
--------------------------------------------------------------------------------------------
使用element UI 上传文件
<el-button
size="small"
type="primary"
@click="selectFile">
Select File
</el-button>
<el-upload
class="upload-demo"
ref="upload" // 标记
name="multipartFile" // 参数名字
accept=".xlsx" // 允许上传的文件类型
:limit='1' // 限制文件个数
:multiple="false" // 是否可以多选
:headers="headers" // 设置请求头
:auto-upload="false" // 是否自动直接上传
:file-list="fileList" // 存放上传文件,用于页面的文件名字展示
:action="uploadAction" // 上传的API
:on-error="handError" // 上传出错的回调
:on-remove="handleRemove" // 删除文件
:on-success="handSuccess" // 上传成功的回调
:http-request="customUpload" // 自定义上传,不依赖element UI 的上传
>
<div slot="tip" class="el-upload__tip">
上传文件的文案说明
</div>
</el-upload>
--------------------------------------------------------------------------------------------
handSuccess(res) {
this.$message.success('File uploads successfully')
this.handleClose()
this.loading = false
this.goSearch()
},
handError(res) {
this.uploadErrorText = 'File uploads failed'
this.loading = false
},
submitUploadFile() {
if (this.$refs.upload.uploadFiles.length) {
// element ui 的自定义上传
this.$refs.upload.submit();
this.loading = true
} else {
this.$message.warning('Please select file')
}
},
selectFile() {
setTimeout(() => {
this.uploadErrorText = ''
}, 2000)
// 唤醒 element UI 的上传事件
this.$refs.upload.$refs['upload-inner'].handleClick();
},handleRemove(file, fileList) {},
------------------------------------------------------------------------
// 使用此函数是需要设置 :http-request="customUpload: , :auto-upload="false"
customUpload() {
let _data = new FormData
_data.append('multipartFile',
this.$refs.upload.$refs['upload-inner']['fileList'][0]['raw'])
uploadFileApi(_data).then(res => {
this.handSuccess()
})
},
--------------------------------------------------------------------------------------------
export function uploadFileApi(params) { return request({
url: `uploadApi`,
method: 'post',
data: params,
})
}
--------------------------------------------------------------------------------------------