Backend Usage
using Nitro Server Engine, we will make an api route that recieves the files and stores them in the folder userFiles
since we have two methods of uploading from the frontend there will be also two methods of handling the request from the backend
Beware of writing the same file name to the same location, here is why.
Multipart Object Method
open a new api route: /server/api/file.ts
Single File
export default defineEventHandler(async (event) => {
const files = (await readMultipartFormData(event)) || []
const fileName = await storeFile(
files[0], // the file object
12, // you can add a name for the file or length of Unique ID that will be automatically generated!
'/userFiles' // the folder the file will be stored in
)
return fileName
})
storeFile
will return the name of the file that was stored
JSON Method
Single File
export default defineEventHandler(async (event) => {
const { files } = await readBody<{ files: File[] }>(event)
const fileName = await storeFileJson(
files[0], // the file object
8, // you can add a name for the file or length of Unique ID that will be automatically generated!
'/userFiles' // the folder the file will be stored in
)
return fileName
})
interface File {
name: string
size: number
type: string
lastModified: date,
content: string,
}
Get File Data
If you need to get the data of the file without storing it you can use the parseDataUrl
Method
const { binaryString, ext } = parseDataUrl(file.content)
This function only works for Base64 files "the JSON method"
Updating Files
If you want to update a file you just have to store a new file with the same name and it will automatically write the new file content to the same file title.
Deleting Files
Get the name and location of the file you want to delete and run it through this command through your api handler
/api/file.ts
await deleteFile(
"fileName.png",
"/specificFolder"
)