Image and File upload

Hello everyone, I've been looking for any document relate to Image upload like (image crate) but I think that not for image upload.
My problem is I want the user can upload image to my back-end (I use Rocket framework and I want the image to store in Postgresql). For example, after they sign up they can upload and view their image later.
Please give me some documents especially examples, I'm new with back-end.
Thank you very much!

It depends whether you want to resize and recompress the files. If you don't need that, then you don't need anything image-specific and it's just a matter of moving a bunch of bytes from one place to another.

  • You need to receive multipart POST request in Rocket.
  • If you want to resize and optimize images, look at docs how to load and save an image (the image crate and resize crate will do). There's also imageflow server that can do all kinds of fancy resizing.
  • Save the received image somewhere to disk. Database is a poor choice for storing images.
  • Find a way to serve static files from that disk location. Either via Rocket, or via something like nginx if your rocket server is behind another server.

Be careful about security — don't allow non-image uploads. If you get tricked into accepting HTML, your site can be attacked with XSS. If you serve static files via a web server that supports PHP or such, then accepting a .php file is a huge danger too.

1 Like

Thank you senior, I will try your solution.

Hello senior, I got some example from online about image upload. But it's not upload to any folder on local storage. When upload image it return Vec.
how can we save that image to local storage?
one more I also want to save it to database, what should I do?
Thank you very much!!!

When you have a vec, you save it to local storage with:

// clean up filename for security:
let file_name = Path::new(image_filename).file_name().unwrap()
  .with_extension("jpg");  // you can set one based on content-type

// this is where the image will be on disk
let full_path =  Path::new("/path/to/your/folder").join(file_name);
std::fs::write(full_path, the_vec)?;

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.