使用vue上傳或下載excel檔案
阿新 • • 發佈:2019-02-02
<form>
<input type="file" name="fileup" id="uploadEventFile" v-on:change="fileChange($event)" style="display:none" />
</form>
<button v-on:click="importData($event)" class="imptbtn">匯入excel</button>
<button v-on:click="download()" class="imptbtn">下載</button>
// 匯入excel檔案
importData: function(event) {
event.preventDefault();
$("#uploadEventFile").trigger("click")
},
fileChange: function (el) {
el.preventDefault();//取消預設行為
let vm = this
let uploadEventFile = $("#uploadEventFile").val()
this.file = el.target.files[0]
if (uploadEventFile == '' ) {
alert("請擇excel,再上傳");
} else if (uploadEventFile.lastIndexOf(".xls") > 0 || uploadEventFile.lastIndexOf(".XLS") > 0) {
let formData = new FormData();
// 向 formData 物件中新增檔案
formData.append('file',this.file);
let config = {
// 一定要定義頭
headers: {
'Content-Type' : 'multipart/form-data'
}
}
// url為對應的後端介面
vm.$http.post(url,formData,config).then(function (response) {
alert('上傳成功')
})
} else {
alert("只能上傳excel檔案");
}
},
// 下載檔案
download: function(){
axios({
method: "get",
url: "xxx",
responseType: "arraybuffer"
})
.then(
function(response) {
let filename = "poiImport.xlsx";
this.fileDownload(response.data, filename);
}.bind(this)
)
.catch(
function(error) {
alert("網路請求出錯");
}.bind(this)
);
},
fileDownload = function (data, fileName) {
let blob = new Blob([data], {
type: "application/octet-stream"
});
let filename = fileName || "filename.xls";
if (typeof window.navigator.msSaveBlob !== "undefined") {
window.navigator.msSaveBlob(blob, filename);
} else {
var blobURL = window.URL.createObjectURL(blob);
var tempLink = document.createElement("a");
tempLink.style.display = "none";
tempLink.href = blobURL;
tempLink.setAttribute("download", filename);
if (typeof tempLink.download === "undefined") {
tempLink.setAttribute("target", "_blank");
}
document.body.appendChild(tempLink);
tempLink.click();
document.body.removeChild(tempLink);
window.URL.revokeObjectURL(blobURL);
}
};