mirror of
https://github.com/TandoorRecipes/recipes.git
synced 2026-01-02 12:49:02 -05:00
basic user file upload working
This commit is contained in:
21
vue3/src/composables/useDjangoUrls.ts
Normal file
21
vue3/src/composables/useDjangoUrls.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* helper function to use django urls while respecting sub path setups
|
||||
* only needed as long as not all pages are integrated into the Vue.js frontend (which might be forever...)
|
||||
*/
|
||||
export function useDjangoUrls() {
|
||||
const basePath = localStorage.getItem('BASE_PATH')
|
||||
|
||||
/**
|
||||
* given a path return the full server url to that url respecting possible sub path setups
|
||||
* @param path
|
||||
*/
|
||||
function getDjangoUrl(path: string){
|
||||
if(path.charAt(0) == '/'){
|
||||
path = path.substring(1)
|
||||
}
|
||||
|
||||
return `${basePath}/${path}`
|
||||
}
|
||||
|
||||
return {basePath, getDjangoUrl}
|
||||
}
|
||||
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