mirror of
https://github.com/TandoorRecipes/recipes.git
synced 2026-01-01 20:28:46 -05:00
basic user file upload working
This commit is contained in:
46
vue3/src/composables/useFileApi.ts
Normal file
46
vue3/src/composables/useFileApi.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import {useDjangoUrls} from "@/composables/useDjangoUrls";
|
||||
import {ref} from "vue";
|
||||
import {getCookie} from "@/utils/cookie";
|
||||
import {UserFile, UserFileFromJSON} from "@/openapi";
|
||||
import {ErrorMessageType, PreparedMessage, useMessageStore} from "@/stores/MessageStore";
|
||||
|
||||
/**
|
||||
* function to upload files to the multipart endpoints accepting file uploads
|
||||
*/
|
||||
export function useFileApi() {
|
||||
const {getDjangoUrl} = useDjangoUrls()
|
||||
|
||||
const fileApiLoading = ref(false)
|
||||
|
||||
function createOrUpdateUserFile(name: string, file: File | null, id?: number): Promise<UserFile> {
|
||||
let formData = new FormData()
|
||||
formData.append('name', name)
|
||||
|
||||
if (file != null) {
|
||||
formData.append('file', file)
|
||||
}
|
||||
|
||||
fileApiLoading.value = true
|
||||
|
||||
let fetchUrl = getDjangoUrl('api/user-file/')
|
||||
let fetchMethod = 'POST'
|
||||
if (id) {
|
||||
fetchUrl += `${id}/`
|
||||
fetchMethod = 'PUT'
|
||||
}
|
||||
|
||||
return fetch(fetchUrl, {
|
||||
method: fetchMethod,
|
||||
headers: {'X-CSRFToken': getCookie('csrftoken')},
|
||||
body: formData
|
||||
}).then(r => {
|
||||
return r.json().then(r => {
|
||||
return UserFileFromJSON(r)
|
||||
})
|
||||
}).finally(() => {
|
||||
fileApiLoading.value = false
|
||||
})
|
||||
}
|
||||
|
||||
return {fileApiLoading, createOrUpdateUserFile}
|
||||
}
|
||||
Reference in New Issue
Block a user