Add a file uploader

This commit is contained in:
Jackson Harper
2022-11-14 11:54:28 +08:00
parent 857fd59199
commit c9771bb2c3
2 changed files with 96 additions and 1 deletions

View File

@ -51,6 +51,7 @@ import {
TypeaheadSearchItemsData,
typeaheadSearchQuery,
} from '../../../lib/networking/queries/typeaheadSearch'
import { uploadFileRequestMutation } from '../../../lib/networking/mutations/uploadFileMutation'
export type LayoutType = 'LIST_LAYOUT' | 'GRID_LAYOUT'
@ -705,9 +706,47 @@ function HomeFeedGrid(props: HomeFeedContentProps): JSX.Element {
const [fileNames, setFileNames] = useState([])
const handleDrop = (acceptedFiles: any) =>
const uploadFiles = useCallback(async () => {
}, [fileNames])
const handleDrop = async (acceptedFiles: any) => {
setFileNames(acceptedFiles.map((file: { name: any }) => file.name))
for (const file of acceptedFiles) {
console.log("FILE: ", file)
try {
const request = await uploadFileRequestMutation({
url: `file://${file.path}`,
contentType: file.type,
createPageEntry: true,
})
const blob = await new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onload = async () => {
resolve(reader.result);
}
reader.onerror = (error) => {
reject(error);
}
reader.readAsDataURL(file);
})
if (!request?.uploadSignedUrl) {
throw 'No upload URL available'
}
const signedUrl = new URL(request?.uploadSignedUrl)
const result = await fetch(signedUrl, {
method: 'PUT',
mode: 'no-cors',
})
console.log('result of uploading: ', result)
} catch {
alert('Error uploading file')
}
}
}
return (
<>
<VStack

View File

@ -0,0 +1,56 @@
import { gqlFetcher } from '../networkHelpers'
import { v4 as uuidv4 } from 'uuid'
type UploadFileInput = {
url: string
contentType: string
createPageEntry?: Boolean
clientRequestId?: string
}
type UploadFileOutput = {
jobId?: string
url?: string
clientRequestId?: string
}
type UploadFileResponseData = {
uploadFileRequest?: UploadFileData
errorCodes?: unknown[]
}
type UploadFileData = {
id: string
uploadSignedUrl: string
}
export async function uploadFileRequestMutation(
input: UploadFileInput
): Promise<UploadFileData | undefined> {
const mutation = `
mutation UploadFileRequest($input: UploadFileRequestInput!) {
uploadFileRequest(input:$input) {
... on UploadFileRequestError {
errorCodes
}
... on UploadFileRequestSuccess {
id
uploadSignedUrl
}
}
}`
if (!input.clientRequestId) {
input.clientRequestId = uuidv4()
}
const data = await gqlFetcher(mutation, { input })
const output = data as UploadFileResponseData | undefined
const error = output?.errorCodes?.find(() => true)
if (error) {
throw error
}
console.log("RESPONSE DATA: ", data)
return output?.uploadFileRequest
}