图片上传:
html部分
<input class="file" name="file" type="file" accept="image/png,image/gif,image/jpeg" @change="update($event)"/>
axios的post请求,发送form数据部分,这样就可以无刷新的提交form数据到后台
methods: {
// 图片上传
update(e) {
let file = e.target.files[0];
let param = new FormData();
param.append("File", file);
console.log(param.get("File"));
let config = {
headers: { "Content-Type": "multipart/form-data" },
}; //添加请求头
this.$http.post("/api/upload", param, config).then((res) => {
if (res.data.status == 200) {
console.log(res.data.data);
this.location = res.data.data
}
});
}
}
需要注意的是:
名字一定要一样,要不然接受不到数据!!!!!!!
使用form表单上传文件
html:
//这里使用了element 的弹窗组件
<el-dialog title="批量导入人员" :visible.sync="importSwipePerson" width="30%" center>
<el-form
ref="importFrom"
:model="importFrom"
label-width="210px"
content="multipart/form-data"
>
<el-form-item label="选择上传">
<input type="file" @change="getFile($event)" />
</el-form-item>
<el-form-item label="模版下载">
<el-button type="success" @click="swipeDownLoad">模板下载</el-button>
</el-form-item>
<el-form-item label="设备型号">
<el-select v-model="importFrom.deviceModelId" placeholder="请选择设备型号">
<el-option
v-for="item in listOptions"
:key="item.appDeviceModelId"
:label="item.appDeviceModelName"
:value="item.appDeviceModelId"
></el-option>
</el-select>
</el-form-item>
</el-form>
<span slot="footer" class="dialog-footer">
<el-button @click="importSwipePerson = false">取 消</el-button>
<el-button type="primary" @click="submitSwipeUpload($event)">提 交</el-button>
</span>
</el-dialog>
methods:
methods:{
getFile(event) {
this.file = event.target.files[0];
console.log(this.file);
},
submitSwipeUpload(event) {
event.preventDefault();
let formData = new FormData();
formData.append("file", this.file);
formData.append("deviceModelId", this.importFrom.deviceModelId);
console.log(formData);
let config = {
"Content-Type": "multipart/form-data",
};
this.$http
.post("/api/posMachine/import", formData, config)
.then((res) => {
console.log(res);
if (res.data.status === 200) {
this.importSwipePerson = false;
// this.importFrom = undefined;
this.$message.success("上传成功");
this.SwipeTableList();
} else {
this.$message.error(res.data.message);
}
});
},
}
模板下载下载功能(excel):
swipeDownLoad() {
Axios({
method: "GET",
url: "/api/posMachine/downLoad",
responseType: "blob",
})
.then((res) => {
let blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
let url = window.URL.createObjectURL(blob);
window.location.href = url;
})
.catch((error) => {
console.log(error);
});
},
参考文档:https://blog.csdn.net/h363659487/article/details/79035388