在写项目时遇到了文件和图片上传的一些需求
网上找了一些上传方式,门槛普遍较高,不适合入学
目前根据搜索到的方法,压缩出了一种特别简单的文件上传方式(只有上传,没有什么优化,适合初学者学习)
使用的是vue框架和elementUI库
第一种 使用它的action方法
首先来看一段代码
<el-upload
class="upload-demo"
:headers="token"
action="http://120.53.31.103:84/api/public/img"
:on-preview="handlePreview"
:on-remove="handleRemove"
:file-list="sizeForm.fileList"
list-type="picture"
:on-success="successImg"
>
<!-- 上传图片 headers提交token action提交地址 on-success成功回调 三个比较重要 -->
//这是标签中的token的数据源 token我们通过headers来进行传递
data() {
return {
token: {
Authorization: "Bearer" + localStorage.getItem("adminToken") || ""
}
};
},
以上代码中,action是图片提交的目标地址;
on-success是成功之后的回调,他有三个参数(请求成功后的回调参数,当前操作上传的文件,点前上传器所有上传的文件列表)
文件到这里后就已经上传到服务器中了
successImg(res, file) {
console.log(res, file);
if (res.code === 200) {
//res.data.path 是服务器返回的当前图片的网络地址
this.sizeForm.avatar = res.data.path;
this.sizeForm.fileList.push(file);
console.log(res.data.path);
}
}
第二种 不使用action方法
<el-upload
class="upload-demo"
action="abc"
:limit="1"
:show-file-list="false"
:before-upload="onprog"
>
<el-button size="small" type="primary">上传文件</el-button>
</el-upload>
这方法就不使用action进行上传了 改成随便的字符串
使用before-upload方法,这是文件上传前的钩子,它的参数就是当前操作的这个文件
执行的函数为
onprog(file) {
//创建formdata实例
var formData = new window.FormData();
//将获取的文件通过append方法加入实例中
formData.append("file", file);
console.log(formData);
//将formdata实例通过接口传递给服务器
req_upDataFile(formData).then(res => {
var type, message;
console.log(res.data);
if (res.data.code === 200) {
//文件内容不符合服务器需求 data的值是一个err数组 若符合data的值是一个数字
if (res.data.data.err) {
// type = "success";
this.err = res.data.data.err;
this.dialogVisible = true;
} else {
type = "success";
message = `共${res.data.data}条,上传成功`;
this.$message({
type,
message
});
}
} else {
this.$message({
type: "error",
message: res.data.msg
});
}
});
}
这里使用了formData这个方法,我们将它实例化后使用append方法将文件存入其中
然后调用接口传入有文件的formData对象就可以了