1. 설명
Jquery를 통해 Ajax를 구현하지 않고, Ajax의 대표적 Api인 Fetch와 XMLHttpRequest를 사용한다.
Javascript의 Fetch 메소드를 사용하여 Get, Post 통신을 진행한다.
파일의 업로드 XmlHttpRequest를 통해서 진행하고 다운로드는 Fetch 메소드의 Get을 이용한다.
2. Fetch
- window.fetch로 사용하였으나, 그냥 fetch로도 사용할 수 있다.
- Promise 기반의 메소드
- Fetch의 파라미터 정보
- Url : Api 주소
- Option : 추가적으로 전송할 데이터
- method : Get / Post / Put / Delete ( Http Method )
- headers : 헤더에 들어갈 정보들, Object 형식이다.
- Response의 메소드
- text(), json(), formData(), blob(), arrayBuffer(), body() : 응답을 해당하는 형식으로 반환
Download 기능 구현을 위해 Response의 header의 Content-Disposition에 attachment라고 명시가 되어있는지 체크 후
Response를 Blob 타입으로 변경하여 저장 기능을 구현한다.
windwo.fetch([Url], [Object - Option]).then(response => {
console.log(response);
});
// 실제 코드
export const Server = {
get: (url: string) => {
return window.fetch(url, {method: "GET", headers: {"Call-Method": "fetch"}}).then(response => {
console.log(response.headers.get("Content-Length") != "0");
}
, post: (url: string, body: any = {}) => {
return window.fetch(url, {
method: "POST",
headers: {"Content-Type": "application/json", "Call-Method": "fetch"},
body: JSON.stringify(body)
}).then(response => response.json());
}
, download : (url : string) => {
let disposition : string | null;
let status : number;
window.fetch(url, {
method: "Get",
headers: {"Call-Method": "fetch"}
}).then(response => {
disposition = response.headers.get('Content-Disposition');
status = response.status;
return response.blob();
}).then(blob => {
let filename = "";
if(disposition && disposition.indexOf('attachment') !== -1) {
const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
const matches = filenameRegex.exec(disposition);
if(matches != null && matches[1]) filename = decodeURI( matches[1].replace(/['"]/g, '') );
}
if (status === 200) saveBlob(blob, filename);
});
}
}
function saveBlob(blob : any, fileName : string) {
let a = document.createElement('a');
a.href = window.URL.createObjectURL(blob);
a.download = fileName;
a.dispatchEvent(new MouseEvent('click'));
}
3. XML Http Request
download는 fetch로 변경하였다.
download를 비교해 보자면 fetch 메소드를 사용하는 것보다는 비교적 xml 객체를 이용한 코드는 가독성이 떨어진다.
upload: (files: FileList, listener? : any) => {
Array.from(files).forEach(file => {
const reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = () => {
const xhr = new XMLHttpRequest();
xhr.open("POST", "/upload");
xhr.setRequestHeader("Simms-File-Name", encodeURIComponent(file.name));
xhr.setRequestHeader("Simms-File-Type", file.type);
xhr.setRequestHeader("Call-Method", "fetch");
xhr.onreadystatechange = () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
const response = JSON.parse(xhr.responseText);
if (listener) listener(response);
}
}
}
xhr.send(reader.result);
}
});
}
, download: (url : string) => {
const xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.setRequestHeader("Call-Method", "fetch");
xhr.responseType = "blob";
xhr.onload = e => {
let filename = "";
const disposition = xhr.getResponseHeader('Content-Disposition');
if (disposition && disposition.indexOf('attachment') !== -1) {
const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
const matches = filenameRegex.exec(disposition);
if (matches != null && matches[1])
filename = decodeURI( matches[1].replace(/['"]/g, '') );
}
if (xhr.status === 200) {
const blob = xhr.response;
saveBlob(blob, filename);
}
}
xhr.send();
}
반응형
'Java > - Pure Java Project' 카테고리의 다른 글
8. Query Generator (0) | 2023.02.16 |
---|---|
7. LocalThread & Transaction ( Runnable ) (0) | 2023.02.13 |
6. Annotation (0) | 2023.02.09 |
5. JNDI : DB Connect (0) | 2023.02.08 |
4. Router (Dynamic Import & Create Class) (0) | 2023.02.07 |