一、接口文件 src/api/file.js
import request from "@u/request";
/**
* 文件上传
* @param data {Object} formData对象 "file"
* @returns {*}
*/
export function uploadFile(data) {
return request({
url: "/file/upload",
method: "post",
data: data,
headers: {
"Content-Type": "multipart/form-data;",
},
transformRequest: [
function () {
return data;
},
],
});
}
二、使用页面示例
<template>
<div class="upload-container">
<el-upload
ref="uploadForm"
:before-upload="beforeUpload"
:http-request="uploadFile"
:limit="limit"
accept="image/png,image/jpg,image/jpeg"
action="string"
class="upload-demo"
multiple
>
<el-button size="small" class="upload-btn" type="primary">
<span class="iconfont icon-shangchuan" />上传文件
</el-button>
</el-upload>
</div>
</template>
<script>
import { uploadFile } from "@i/file";
export default {
name: "UploadFile",
props: {
limit: {
type: Number,
default: 1,
},
},
data() {
return {};
},
computed: {},
methods: {
// 上传文件
uploadFile(item) {
// 开始上传文件 新建一个formData
const formData = new FormData();
// 通过append向form对象添加数据
formData.append("file", item.file);
uploadFile(formData)
.then((e) => {
console.log("上传成功");
})
.catch((e) => {
console.log("上传失败");
this.clearFlies();
});
},
// 移除上传图片列表
clearFlies() {
this.$refs.uploadForm.clearFiles();
},
// 上传文件之前
beforeUpload(file) {
const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
const extension1 = fileSuffix === "png";
const extension2 = fileSuffix === "jpg";
const extension3 = fileSuffix === "jpeg";
const isLt2M = file.size / 1024 / 1024 < 0.5;
if (!extension1 && !extension2 && !extension3) {
this.$msg("上传文件只能是 png、jpg、jpeg格式", "error");
return false;
}
if (!isLt2M) {
this.$msg("上传文件大小不能超过 2MB", "error");
return false;
}
},
},
};
</script>
<style lang="scss" scoped>
.upload-container {
.upload-demo {
display: flex;
.upload-btn {
background-color: #525252;
border: none;
}
}
}
</style>