파일 공유
개요
이 문서는 채팅 시스템에서 파일 공유 기능을 구현하는 방법을 설명합니다. 별도의 API 키 발급이나 CMS 설정 없이 쉽게 파일 업로드 및 공유 기능을 추가할 수 있습니다.
구현 절차
1. 기본 설정
먼저 Overview의 내용에 따라 기본 채팅 시스템을 설정합니다.
2. FileUtil 초기화 및 설정
script.js
에 다음 코드를 추가합니다.
js
/**
* 비공개 채팅방 ID를 가져오는 함수
* @returns {string} 비공개 채팅방 ID
*/
function getPrivateRoomId() {
return privateChannel.roomId;
}
/**
* 파일 업로드 완료 후 실행되는 콜백 함수
* @param {boolean} flag - 업로드 성공 여부
* @param {object} res - 업로드된 파일 정보
* @param {boolean} isPrivate - 비공개 채팅방 여부
*/
function fileUpdate(flag, res, isPrivate) {
if (flag) {
if (isPrivate) {
fileUtil.privateRoomId = getPrivateRoomId(); // 비공개 채팅방 ID 설정
}
// 파일 정보 객체 생성
const fileInfo = [
{
id: res.fileKey,
name: res.fileNm,
type: res.fileExt,
size: res.fileSize,
expire: res.expire,
},
];
// 메시지 데이터 구성
const data = {
message: JSON.stringify(fileInfo),
messageType: JSON.stringify({ profile: channel.userInfo.profile }),
mimeType: "file",
};
// 적절한 채널로 메시지 전송
if (isPrivate === true) {
privateChannel.sendMessage(data);
} else {
channel.sendMessage(data);
}
} else {
console.error("파일 업로드에 실패했습니다.");
}
}
/**
* 파일 업로드 진행 상황을 표시하는 콜백 함수
* @param {number} progress - 업로드 진행률 (0-100)
*/
function showProgress(progress) {
console.log(`업로드 진행률: ${progress}%`);
// 필요시 프로그레스 바 UI 업데이트 코드 추가
}
// FileUtil 인스턴스 초기화
const fileUtil = new FileUtil({
isPrivate: true, // 비공개 채팅방 사용 여부
roomId: channelKey, // 메인 채널 키
privateRoomId: getPrivateRoomId, // 비공개 채팅방 ID 가져오는 함수
uploadTag: ".chat-popup-file", // 파일 업로드 버튼 선택자
updateEvent: fileUpdate, // 업로드 완료 후 콜백
uploadDragTag: ".chat-contents", // 드래그&드롭 영역 선택자
progressTag: ".chat-contents", // 프로그레스 표시 영역 선택자
progressSize: 60, // 프로그레스 요소 크기
progressEvent: showProgress, // 업로드 진행 중 콜백
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
3. 파일 업로드 테스트
구현 후 파일 업로드 및 다운로드 기능이 정상적으로 작동하는지 확인합니다.
- 업로드 버튼을 클릭하여 파일 선택
- 채팅 영역에 파일을 드래그&드롭
- 업로드된 파일이 채팅에 표시되는지 확인
4. 파일 조회 및 다운로드 구현
4.1 파일 다운로드
fileInTag
메서드를 사용하면 파일 정보와 다운로드 버튼이 포함된 HTML을 생성할 수 있습니다.- 생성된 HTML을 원하는 영역에 append하여 사용하세요.
js
const fileHtml = fileUtil.fileInTag(
"파일명.pdf", "pdf", "2025-12-31", 1048576, "fileKey123"
);
$("#fileList").append(fileHtml);
1
2
3
4
2
3
4
4.2 파일 타입 체크
js
const type = fileUtil.getFileType("sample.png"); // "image", "video", "audio", "file"
1
4.3 파일 미리보기(이미지/비디오/오디오)
js
channel.onNotifyMessage = function (event) {
if (event.mimeType === 'file') {
fileWrite(event);
} else {
// ... 기존 코드
}
}
function fileWrite(msg, pre, isPrivate) {
let data = JSON.parse(msg.message)[0];
if (data) {
let param = {
profile: "profile-1",
clientKey: msg.clientKey,
nickName: msg.nickName,
};
if (msg?.userInfo?.profile) {
param.profile = `profile-${msg.userInfo.profile}`
}
fileUtil.loadCheck({
ext: data.type,
key: data.id,
imgLoad: function (key) {
param['imgKey'] = key;
param['tag'] = $('<div>', { class: 'fileComment' });
// 화면에 HTML생성 및 삽입
write(param, 'fileSend', pre, isPrivate);
},
vodLoad: function (key) {
param['vodKey'] = key;
param['tag'] = $('<div>', { class: 'fileComment' });
write(param, 'fileSend', pre, isPrivate);
},
audioLoad: function (key) {
param['aodKey'] = key;
param['tag'] = $('<div>', { class: 'fileComment' });
write(param, 'fileSend', pre, isPrivate);
},
fileLoad: function () {
param['tag'] = fileUtil.fileInTag(data.name, data.type, `~ ${data.expire}`, data.size, data.id);
write(param, 'fileSend', pre, isPrivate);
},
});
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
파라미터 설명
FileUtil 초기화 옵션
파라미터 | 타입 | 필수 여부 | 설명 |
---|---|---|---|
isPrivate | Boolean | 비공개 채팅방 사용 여부 설정 | |
roomId | String | ✅ | CMS에서 발급받은 채널 키 값 |
privateRoomId | Function | 비공개 채팅방 사용 시 필수. 비공개 채팅방의 ID를 반환하는 함수 | |
uploadTag | String | ✅ | 파일 업로드 대화상자를 표시할 요소의 CSS 선택자 |
updateEvent | Function | ✅ | 파일 업로드 완료 후 실행되는 콜백 함수 |
uploadDragTag | String | 드래그&드롭으로 파일 업로드를 지원할 영역의 CSS 선택자 | |
progressTag | String | ✅ | 업로드 진행 상태를 표시할 요소의 CSS 선택자 |
progressSize | Number | 프로그레스 요소의 크기 (기본값: 60px) | |
progressEvent | Function | 파일 업로드 진행 중 주기적으로 호출되는 콜백 함수 |
파일 업로드 결과 객체 (res)
속성 | 타입 | 설명 |
---|---|---|
fileKey | String | 업로드된 파일의 고유 식별자 |
fileNm | String | 파일의 원본 이름 |
fileExt | String | 파일의 확장자 또는 MIME 타입 |
fileSize | Number | 파일 크기 |
expire | String | 파일의 만료 일자 (서버 설정에 따름) |
주의사항 및 팁
- 파일 업로드는 100MB이하의 파일만 업로드할 수 있습니다.
- 파일은 설정된 기간 동안만 서버에 저장되며, 업로드한 뒤 일주일 이후에는 자동으로 삭제됩니다.
문제 해결
- 파일 업로드 실패 시 네트워크 연결 및 파일 크기를 확인하세요.
- 비공개 채팅방 기능 사용 시
privateRoomId
함수가 올바르게 설정되었는지 확인하세요.