Downloading files via streams

73 views Asked by At

I have a rest api that uses jax-rs under the hood. Unfortunately I am unable to actually save files on the server/s3 etc. instead I am using JCR via Magnolia CMS to save files (not exactly a fan). There is also a specific way I have to save my files - saving individual file chunks as a bunch of nodes. When I want to download this "file" I stream the chunks via a rest endpoint.

StreamingOutput stream = new StreamingOutput() {
                @Override
                public void write(OutputStream output) throws IOException {
                    try {
                        for (int i = 0; i <= sliceCount; i++) {
                            Node chunkNode = getNode(String.valueOf(i));
                            Binary chunk= chunkNode .getProperty("data").getBinary();
                            InputStream in = chunk.getStream();
                            output.write(in.readAllBytes());
                            output.flush();
                        }
                    } catch (RepositoryException ex) {
                        // exception handling
                    } finally {
                        output.close();
                    }

                }
            };

Afterwards I set all the necessary headers like Content-Length, Content-Disposition with attachment and filename, Content-Type as octetstream. The way I am currently consuming this inside my frontend app is by using StreamSaver, however that is no longer seen as optimal (3rd party cookies settings block seem to block StreamSaver). So I tried just using a simple anchor tag <a href="fileUrl" download> to download the files. Which works, it does download the file, but I've noticed this thing happening - the app tab starts "loading" - displaying a loader.

When I attempt to download multiple files at the same time, every previous download gets cancelled and instead the most recently clicked file gets downloaded. Is there anything that I could do to prevent this from happening - allowing multiple file downloads without this whole loading spinner thing going on?

Creating a blob on the frontend + creating an a tag + clicking it is not really an option for me, cause the files might end up being larger (max 2gb). Storing the files in a more "normal" way is not really an option either, if it were up to me I'd just dump the files on s3 and call it a day.

Edits

  • Have only tested the <a> tag loader thing on localhost, have not tried deploying yet.
  • Backend running on Java 11, using Magnolia CMS 6.2.40
  • Frontend - Nextjs v12
0

There are 0 answers