js / javascript / 엑셀 업로드 / excel / csv upload / vue / vue code / csv upload
browser에서 파일로 file 을 읽어서, 화면에 뿌려주는 js 코드
아래는 vuejs code 이다.
// MyComponent.vue
<template>
<div :class="klass">
<input type="file" @change="onChangeInputFile"/>
<h3>contents of the file:</h3>
<pre>{{fileContent}}</pre>
</div>
</template>
<script>
const _ = {
name: 'MyComponent',
components: {},
props: {
},
data() {
return {
fileContent: "",
}
},
methods: {
onChangeInputFile(e){
const file = e.target.files[0];
if (!file) {
return;
}
const isUtf = await _isUtf8(file)
let encoding = ""
if(!isUtf){
encoding = "euc-kr"
}
const reader = new FileReader();
reader.onload = (e) => {
const contents = e.target.result;
this.fileContent = contents
};
reader.readAsText(file, encoding);
},
},
}
function _isUtf8(file, callback) {
const slice = file.slice(0, 10)
const fr = new FileReader()
const promise = new Promise(function (resolve, reject) {
fr.onload = (e) => {
// e.target.result : ArrayBuffer
const view = new Uint8Array(e.target.result)
// EF BB BF
// 0xef, 0xbb, 0xbf
let isUtf = false
if (view[0] === 239 && view[1] === 187 && view[2] === 191) {
isUtf = true
} else {
// do nothing
isUtf = false
// console.error('File has byte order mark (BOM)')
}
resolve(isUtf)
}
})
fr.readAsArrayBuffer(slice)
return promise
}
export default _
</script>
<style>
</style>
댓글 없음:
댓글 쓰기