// Modal that allows upload of an image to the server import React from "react" import { Image } from "@mwater/expressions" import * as formUtils from "./formUtils" import ModalPopupComponent from "@mwater/react-library/lib/ModalPopupComponent" interface BaseImageUploaderModalComponentProps { apiUrl: string client: string | null onCancel: () => void /** Localizer to use */ T: (str: string, ...args: any[]) => string /** True to force use of camera */ forceCamera?: boolean } interface SingleImageUploaderProps extends BaseImageUploaderModalComponentProps { allowMultiple: false onSuccess: (image: Image) => void } interface MultipleImageUploaderProps extends BaseImageUploaderModalComponentProps { allowMultiple: true onSuccess: (images: Image[]) => void } export type ImageUploaderModalComponentProps = SingleImageUploaderProps | MultipleImageUploaderProps interface ImageUploaderModalComponentState { xhr: XMLHttpRequest | null percentComplete: number | null } export default class ImageUploaderModalComponent extends React.Component { static show(options: { apiUrl: string client: string | null T: (str: string, ...args: any[]) => string success: (image: Image) => void forceCamera?: boolean allowMultiple?: false }): void static show(options: { apiUrl: string client: string | null T: (str: string, ...args: any[]) => string success: (images: Image[]) => void forceCamera?: boolean allowMultiple: true }): void static show(options: { apiUrl: string client: string | null T: (str: string, ...args: any[]) => string success: ((image: Image) => void) | ((images: Image[]) => void) forceCamera?: boolean allowMultiple?: boolean }): void { const { apiUrl, client, T, success, forceCamera, allowMultiple } = options ModalPopupComponent.show((onClose: any) => { return ( { onClose() // allowMultiple decides which overload, and so which callback, the caller passed ;(success as (imageOrImages: Image | Image[]) => void)(imageOrImages) }} /> ) }) } constructor(props: ImageUploaderModalComponentProps) { super(props) this.state = { xhr: null, // Upload xhr percentComplete: null // Percent upload completed } } handleCancel = () => { this.state.xhr?.abort() } handleFileSelected = async (ev: React.ChangeEvent) => { if (!ev.target.files || ev.target.files.length === 0) { return } // Calculate total size let totalSize = 0 for (const file of ev.target.files) { totalSize += file.size } // Store uploaded size let uploadedSize = 0 let images: Image[] = [] try { for (const file of ev.target.files) { const image = await this.uploadFile(file, totalSize, uploadedSize) images.push(image) uploadedSize += file.size } } catch (error) { alert((error as Error).message) } if (this.props.allowMultiple) { this.props.onSuccess(images) } else { this.props.onSuccess(images[0]) } } uploadFile(file: File, totalSize: number, uploadedSize: number): Promise { return new Promise((resolve, reject) => { if (file.type !== "image/jpeg" && file.type !== "image/png" && !file.name.match(/\.(jpe?g|png)$/i)) { reject(new Error(this.props.T("Image must be a JPEG or PNG file"))) return } const xhr = new XMLHttpRequest() const fd = new FormData() fd.append("image", file) // Create id const id = formUtils.createUid() // Add event listners xhr.upload.onprogress = (evt) => { let percentComplete if (evt.lengthComputable) { percentComplete = Math.round(((evt.loaded + uploadedSize) * 100) / totalSize) this.setState({ percentComplete }) } else { this.setState({ percentComplete: ((uploadedSize + file.size) * 100) / totalSize }) } } xhr.addEventListener("load", (evt) => { // This event is raised when the server sends back a response if (xhr.status === 200) { resolve({ id }) } else { reject(new Error(this.props.T("Upload failed: {0}", xhr.responseText))) } }, false) xhr.addEventListener("error", () => { reject(new Error(this.props.T("Error uploading file. You must be connected to the Internet for image upload to work from a web browser."))) }, false) xhr.addEventListener("abort", () => { reject(new Error(this.props.T("Upload cancelled"))) }, false) // Generate url let url = this.props.apiUrl + "images/" + id + "?autoOrient=true" if (this.props.client) { url += "&client=" + this.props.client } // Set that uploading (start at 100% in case no updates) this.setState({ xhr, percentComplete: 100 }) // Begin upload xhr.open("POST", url) xhr.send(fd) }) } renderContents() { return (
{isMobile() ? <> {" "} {!this.props.forceCamera ? : null} : }
{this.state.xhr ? ( <>
{this.props.T("Uploading")} {this.state.percentComplete}%
) : undefined}
) } render() { return ( {this.renderContents()} ) } } function isMobile() { const mobileRegex = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i return mobileRegex.test(navigator.userAgent) }