상품등록 할 때 이미지 주소를 가져오면 그 이미지를 가지고 오는 로직을 가진 파일 업로드 컴포넌트가 있었다.
이것도 나름의... 개선을 한 거였는데(그 전에는 이미지를 직접 파일로 올렸어야만 했음)
우리한테 들어오는 입점처들이 상품 정보에 관련된 걸 예쁘게 정리해서 주는 곳은 거~~~의 없어서 노가다가 너무 심했다고 한다.
그걸 url로 가지고 올 수 있게 하면서 조금은 편해졌나... 했는데 이런!
어떤 사이트의 이미지들은(정확히 원인은 알 수 없지만 일종의 보안과 관련된 이유라고 추측) 이미지 url을 이용해서 이미지를 가져오면 깨져서 등록되거나 거부되는 경우가 많았다!
그 때에는 어쩔 수 없이 담당자가 그 이미지를 컴퓨터에 다운로드 받아서 다시 파일 업로드를 해야 하는 최초의 방식으로 진행했는데 명절을 맞아 업무가 과부하 되면서 기능 개선의 요청이 들어왔다.
그것은 바로~! "이미지 복사"를 해서 바로 붙여넣기가 되게 해달라는 것.
생각해보니까 이 기능 나도 엄청 편리하게 쓰고 있었는데 첨부터 해 줄 생각을 딱히 못했네...^^;;;
심지어 어려울 것 같아서 빨리 될 수 있을지 모르겠다 했는데 매우 쉬웠다.
아래와 같은 함수를 만들고 그 함수를 동작하는 input 태그에 onPaste 로 걸어주니 바로 실행되었다.
const handlePaste = async (event: React.ClipboardEvent) => {
const items = event.clipboardData.items;
const files: File[] = [];
for (let i = 0; i < items.length; i++) {
if (items[i].type.indexOf('image') !== -1) {
const file = items[i].getAsFile();
if (file) files.push(file);
}
}
if (files.length > 0) {
const validatedFiles = await getValidatedFiles(files, requiredConditions);
await addFiles(validatedFiles);
event.preventDefault();
}
};
- The Three Main Types
There are three events associated with this type:
onCopy: Fires when the user initiates a "copy" action.
onCut: Fires when the user initiates a "cut" action.
onPaste: Fires when the user initiates a "paste" action.
- The clipboardData Property
The most important part of a ClipboardEvent is the clipboardData property. It is a DataTransfer object that acts as a container for the data being moved.
It has several key methods and properties:
getData(format): Retrieves text or data from the clipboard (usually used in onPaste).
setData(format, data): Modifies what gets put onto the clipboard (usually used in onCopy).
items: A list of DataTransferItem objects. This is crucial for handling files or images (as we saw in your previous question).
files: A list of files being pasted.