2

I am able to upload files at the default location.

router.route().handler(
  BodyHandler.create()
    .setBodyLimit(500 * KB)
);    
router.post("/admin/add").handler(adminActions::createNewItem);

This body handler puts file in file-uploads. This is the code that uploads files:

public void createNewItem(RoutingContext context) {
    var request = context.request();
    var type = context.request().getFormAttribute("type");

    // other code...    

    for(var f : context.fileUploads()) {
      System.out.println(f.fileName());
    }            
  }

These are the files I have uploaded.

enter image description here


The file-uploads folder is at the root of my project, it's been automatically created. How do I reach the content of that folder to show the images in my html pages?

It's weird also, they have no extension...

Emma Rossignoli
  • 935
  • 7
  • 25

2 Answers2

3

Vert.x can serve static content with the static handler:

router.route("/static/*").handler(StaticHandler.create());

The static handler webroot can be configured to point to your file uploads directory.

Yet I would recommend to consider security carefully if you are working on a public service with private data: if you expose the content of this directory without any protection, malicious users could try to download arbitrary content.

tsegismont
  • 8,591
  • 1
  • 17
  • 27
0

In addition to what user tsegismont said I have to explain what's going on. I already used the statichandler but not in the proper way.

enter image description here

This is what I had before. The folder resource is inside src > main > java and I wanted to put pics there but it was not possible; this folder is compiled and I should restart the app every time that an upload occurs to see pictures. Not a good idea.

SOLUTION. I created a folder called image-uploads at the same level of src and then I used this code:

router.route("/uploads/imgs/*").handler(
      StaticHandler.create("image-uploads").setCachingEnabled(false)
);

And it works! When I call https://mywebsite.com/uploads/imgs/something.png vertx goes in the image-uploads folder and serves the images.


So if you want to upload images to the server and then see them in the browser via link, DO NOT upload files in src or subfolders. Do it outside src. Oh and when you upload do this:

router.route().handler(
  BodyHandler.create()
    .setUploadsDirectory("image-uploads")
    .setBodyLimit(400 * KB)
    .setMergeFormAttributes(true)
);

In this way setUploadsDirectory points to the folder outside src in which I put data.

Emma Rossignoli
  • 935
  • 7
  • 25