웹서버에 올려져 있는 파일은 Fetch 함수를 통해 읽어온다. 그런데 이 Fetch 함수 주소에 http://localhost:8080/ 이렇게 넣어서 읽어오려면 웹브라우저 보안 때문에 아래와 같이 CORS Error가 생긴다.
blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.
이것을 해결하기 위해 html로 로컬 파일을 지정해서 읽는 두 단계로 진행해야 문제를 해결할 수 있다.
html에 아래 코드 추가
<form>
<div>
<label for="input_file">파일을 추가해주세요.</label>
<input type="file" id="input_file">
</div>
<div>
<button onclick="test(event)">summit</button>
</div>
</form>
자바스크립트에 아래 코드 추가
function test(event) {
event.preventDefault(); //submit 할때 새로고침 되는것을 방지
let fileObject = document.getElementById("input_file");
let fileName = fileObject.files[0];
let fr = new FileReader();
fr.readAsText(fileName, "utf-8");
fr.onload = () => {
parseText(fr.result);
}
}
function parseText(text) {
console.log(text)
// 이 아래에 text string을 처리하는 코드를 넣으면 됨
}
}
'HTML with 자바스크립트 > 파일 입출력' 카테고리의 다른 글
자바스크립트 제이슨 파일 읽기 (0) | 2022.12.21 |
---|