skip to Main Content

I save my image with writeFile but i can’t load it in my browser.
Except if i restart (npm run dev || node build/index)

await writeFile("static/img/tmp/"+now+".jpg", contentReplace, 'base64');

I use SvelteKit with node-adapter, i don’t want to use s3 or anything else because is only for uploading one file the be deleted after an other operation.

I’ve tried to save my image in many different folders:

  • build/client/img/tmp
  • src/lib/images/tmp
  • static/img/tmp

2

Answers


  1. Chosen as BEST ANSWER

    Thanks brunnerh,

    After your answer, i've created new route and file in

    src/routes/api/image/get/[id]/post.jpg/+server.svelte

    Then in this file i wrote this code :

    import { error } from '@sveltejs/kit';
    
    import Image from "$controllers/ImageController.js";
    
    /** @type {import('../../../$types').RequestHandler} */
    export async function GET({ params, locals, setHeaders }) {
        const session = await locals.session.data;
        const {id} = await params;
    
        let img = await Image.getById(id);
    
        if(!img)
            error(404, "Cette image n'existe pas");
    
        if(img.published !== "Y" && !session.userid)
            error(404, "Cette image n'existe pas");
    
        setHeaders({
            'Content-Type': 'image/jpg'
        });
        
        img.content = img.content.replace(/^data:image/[a-z]+;base64,/, "");
        
        const pageImage = Buffer.from(img.content, 'base64');
    
        return new Response(pageImage )
    }
    

    Now i can access to my file in https://my-domain.com/api/image/get/[id]post.jpg and i don't have to save img in server folder, get url and delete img.

    Of course before, i send image with an html input, i transform img in base64 and i save in my database.


  2. The application will only serve files known at build time.
    (You can see the listed files and routes in the build/server/manifest.js.)

    If you want to support uploading/serving of dynamic files you either have to serve the files via its own route that reads the files manually or set up a custom server using the built handler for the regular application logic and some static asset middleware that additionally serves you uploads directory.

    (Given that the files are to be deleted after use, you could also just store the file in memory and serve it from there, then you don’t need to deal with the file system at all.)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search