Search code examples
javaspringtomcat

How to handle file uploading and sharing them as an URL (not returning them) in spring boot app?


That is my first question on SO, so I will try to describe my problem as detailed as possible. I have a REST spring api on backend and angular app at frontend. I tried to implement following functionality:

  1. User at front uploades an image.
  2. Api receives the image, saves it and generates an URL for this file.
  3. User is able to display the image based on the received URL.

My question is following: How should it be done? I would not like to save image to a database - I would rather prefer to store just the URL. I have read there is a possibility to share files in Tomcat (embedded for Spring Boot), but I do not actually know how that works (I am a begginer, so please forgive :)). Could someone explain how does it work, and if it is a soultion for my problem? ).

I tried to save image on my local disk, then share the URL to frontend - unfortunately there was an cors-error, when I tried to display the image.


Solution

  • For servlet stack applications, the spring-boot-starter-web (defined in your pom.xml or which dependency mng you use for file) includes Tomcat by including spring-boot-starter-tomcat , but you can use spring-boot-starter-jetty or spring-boot-starter-undertow instead. If you want to change your application server or getting information, here is the official document

    For avoiding cors error , please check related solutions . It might be related your API headers or browser.

    If you want a store exact picture , you can save as BLOB(binary large object) column type. Here is the example project but you need some spesific practise for your improvement. Example project : upload and download with spring boot

    At the beginning section , you should learn application context , bean scope and basically background of spring framework before developing api with spring boot to getting knowledge of fundemantals.

    i hope it helps.