Created
July 2, 2023 14:31
-
-
Save sortofsleepy/a846ca01a171ac9857e670aef13f52d5 to your computer and use it in GitHub Desktop.
SvelteKit File Upload Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]}` | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 calledtmp
.Adjust as needed.