Skip to content

Instantly share code, notes, and snippets.

@sortofsleepy
Created July 2, 2023 14:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sortofsleepy/a846ca01a171ac9857e670aef13f52d5 to your computer and use it in GitHub Desktop.
Save sortofsleepy/a846ca01a171ac9857e670aef13f52d5 to your computer and use it in GitHub Desktop.
SvelteKit File Upload Example
import {writeFileSync, existsSync, mkdirSync} from "fs"
// make sure tmp directory exists and create it if it doesn't
function checkTmp() {
if (!existsSync("static/tmp")) {
mkdirSync("static/tmp")
}
}
export const actions = {
/**
* Handles upload and saves file in tmp folder.
* Returns error + code if something happens, otherwise returns
* filename to pass onto the next stage.
*/
upload: async ({request}: any) => {
const formData = Object.fromEntries(await request.formData());
// split filename into name + extension
let name = formData.video.name;
name = name.split(".")
// get buffer to video
let video = await formData.video.arrayBuffer()
checkTmp()
let error = false
let error_msg = null
try {
writeFileSync(`static/tmp/${name[0]}.${name[1]}`, Buffer.from(video))
} catch (e) {
error = true
error_msg = e
}
if (error) {
return {
code: -1,
msg: error_msg.code
}
} else {
return {
code: 200,
filename: `${name[0]}.${name[1]}`
}
}
}
}
@sortofsleepy
Copy link
Author

A basic example of how to do file upload. Waits for form data that sends an input file with the name video, writes it to directory called tmp.

Adjust as needed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment