-
Notifications
You must be signed in to change notification settings - Fork 6
/
FileUploaderWithPreview.tsx
54 lines (44 loc) · 2.04 KB
/
FileUploaderWithPreview.tsx
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
import { useRef, Dispatch, SetStateAction, RefObject, memo } from "react";
import FileUploader from "devextreme-react/file-uploader";
import { useEvent } from "./utils";
import { backendURL } from "./constants";
import { UploadedEvent, UploadErrorEvent, ValueChangedEvent } from 'devextreme/ui/file_uploader';
import { ColumnEditCellTemplateData } from "devextreme/ui/data_grid";
type FileUploaderPreviewProps = {
cellInfo: ColumnEditCellTemplateData,
setRetryButtonVisible: Dispatch<SetStateAction<boolean>>,
fileUploaderRef: RefObject<FileUploader>
}
export const FileUploaderWithPreview = memo(({ setRetryButtonVisible, cellInfo, fileUploaderRef }: FileUploaderPreviewProps) => {
const imgRef = useRef<HTMLImageElement>(null);
const onValueChanged = useEvent((e: ValueChangedEvent) => {
const reader = new FileReader();
reader.onload = function (args) {
if (typeof args.target?.result === 'string') {
imgRef.current?.setAttribute('src', args.target.result);
}
}
reader.readAsDataURL(e.value![0]); // convert to base64 string
});
const onUploaded = useEvent((e: UploadedEvent) => {
cellInfo.setValue("images/employees/" + e.request.responseText);
setRetryButtonVisible(false);
});
const onUploadError = useEvent((e: UploadErrorEvent) => {
let xhttp = e.request;
if (xhttp.status === 400) {
e.message = e.error.responseText;
}
if (xhttp.readyState === 4 && xhttp.status === 0) {
e.message = "Connection refused";
}
setRetryButtonVisible(true);
});
return (
<>
<img ref={imgRef} className="uploadedImage" src={`${backendURL}${cellInfo.value}`} alt="employee pic" />
<FileUploader ref={fileUploaderRef} multiple={false} accept="image/*" uploadMode="instantly"
uploadUrl={backendURL + "FileUpload/post"} onValueChanged={onValueChanged}
onUploaded={onUploaded} onUploadError={onUploadError} />
</>)
})