[Vue] binary 로 변환하는 작업
2023. 6. 13. 09:26ㆍVue
728x90
file로 업로드한 파일과, 캡쳐한 3가지 이미지를 binary 형태로 서버에 보내는 작업
<input id="file" ref="mainImageFile" type="file" @change="uploadFile" >
multiCapture() {
// 파일 선택한 input 엘리먼트
const fileInput = this.$refs.mainImageFile;
// 파일을 Blob 형식으로 변환하는 함수
const convertFileToBlob = (file) => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => {
const blob = new Blob([reader.result], { type: file.type });
resolve(blob);
};
reader.onerror = reject;
reader.readAsArrayBuffer(file);
});
};
// 이미지 캡쳐 및 formData에 추가하는 함수
const captureAndPushImage = (refName, formDataKey) => {
return new Promise((resolve) => {
html2canvas(this.$refs[refName], { backgroundColor: null, scale: 1 })
.then(canvas => {
const imageBlob = this.convertDataURItoBlob(canvas.toDataURL('image/png'))
this.formData[formDataKey].push(imageBlob)
resolve()
})
});
};
// img1을 Blob 형식으로 변환하여 formData에 추가하는 함수
const pushImg1ToFormData = () => {
return new Promise((resolve, reject) => {
const file = fileInput.files[0]; // 선택한 파일 가져오기
convertFileToBlob(file)
.then(blob => {
this.formData['img1'].push(blob);
resolve();
})
.catch(reject);
});
};
// captureAndPushImage 함수 실행
const promises = [];
promises.push(captureAndPushImage('previewTwo', 'img2'));
promises.push(captureAndPushImage('previewThree', 'img3'));
promises.push(captureAndPushImage('previewFour', 'img4'));
// img1을 formData에 추가하는 함수 실행
promises.push(pushImg1ToFormData());
Promise.all(promises)
.then(() => {
const params = {
formData: this.formData,
type: 'wysiwyg'
};
this.$store.dispatch('creative/updateCreative', params)
.then(res => {
this.printJSON = res.message;
})
.catch(error => {
this.hideLoading();
console.error('Error:', error);
});
})
.catch(error => {
this.hideLoading();
console.error('Error capturing images:', error);
});
},
'Vue' 카테고리의 다른 글
[Vue] 문자열 길이 픽셀로 가져오기 (0) | 2023.06.21 |
---|---|
[Vue] 파일업로드 사이즈 / 용량 체크 (0) | 2023.06.14 |
[Vue] router guard (0) | 2023.02.24 |
[Vue] vuex-persistedstate (0) | 2023.02.20 |
[Vue] input[file] 파일 업로드 미리보기 (0) | 2023.02.10 |