如何實(shí)現(xiàn)從本地的文件夾導(dǎo)入文件并上傳?
clipboard.png
- html部分督怜,只實(shí)現(xiàn)瀏覽文件按鈕
<input
type="file"
ref="clearFile"
style="display:none"
@change="upload($event)"
class="add-file-right-input"
accept=".csv"
/>
<a-button @click="goFile" size="small" type="primary">
<a-icon type="upload" />瀏覽文件
</a-button>
- js部分
methods:{
/* ===== 按鈕點(diǎn)擊上傳文件觸發(fā)input文件 === */
goFile() {
this.$refs.clearFile.click();//上傳文件
},
/* =====input file上傳文件事件=== */
upload(event) {
let file = event.target.files;//target事件
let size = file[0].size;//獲取文件大小
size = size / (1024 * 1024);
for (let i = 0; i < file.length; i++) {
// 上傳類型判斷
let imgName = file[i].name;
let idx = imgName.lastIndexOf(".");
if (idx != -1) {
let ext = imgName.substr(idx + 1).toUpperCase();
ext = ext.toLowerCase();
if (ext != "csv") {
return;
} else {
this.addArr.push(file[i]);
this.uploadName = file[0].name;
}
}
}
// 上傳文件大小
if (size > 5) {
this.uploadName = "";
this.$message.error("文件大小5MB!");
}
this.$refs.clearFile.value = ""; //上傳文件后重置
},
handleSubmit() {
this.$refs.ruleForm.validate(valid => {
if (valid) {
if (0 == this.addArr.length) {
this.$message.error("請(qǐng)選擇要上傳的文件");
return;
}
// 通過FormData將文件轉(zhuǎn)換為二進(jìn)制數(shù)據(jù)
let formData = new window.FormData();
//將文件轉(zhuǎn)換為二進(jìn)制
formData.append("type", this.form.type);
formData.append("key_ver", this.form.key_ver);
for (var i = 0; i < this.addArr.length; i++) {
formData.append("file", this.addArr[i]);
}
let config = {
headers: {
type: "file"
}//這個(gè)地方是表單上傳文件的請(qǐng)求頭
};
this.confirmLoading = true;
this.$httpPost(
"········",//請(qǐng)求接口
formData,
config
)
.then(({ code, desc }) => {
this.confirmLoading = false;
if (code === "0") {
this.addArr = [];
this.$message.success("操作成功!");
this.$parent.getData();
this.handleCancel(1);
} else {
this.$message.error(desc);
}
})
.catch(() => {
this.$message.success("操作失敗!");
this.confirmLoading = false;
});
}
});
},
}
},
注:
1.target事件屬性可返回事件的目標(biāo)節(jié)點(diǎn)(出發(fā)該實(shí)踐的節(jié)點(diǎn))魄宏,如生成事件的元素、文檔或者窗口台盯。
2.file屬性
- name: 文件名罢绽,該屬性只讀
- size:文件大小,單位為字節(jié)静盅,該屬性只讀
- type: 文件類型良价,該屬性只讀
- lastModified:文件的上次修改時(shí)間,格式為時(shí)間戳
- lastModifiedDate:文件上次我修改的時(shí)間蒿叠,格式為Date對(duì)象實(shí)例
3.FormData創(chuàng)建對(duì)象(將本地?cái)?shù)據(jù)上傳或者導(dǎo)入數(shù)據(jù)庫的時(shí)候需要使用到FormData對(duì)象)明垢,可以將所有的表單元素的name和value組成一個(gè)queryString提交到后臺(tái).