perwendel / spark

A simple expressive web framework for java. Spark has a kotlin DSL https://github.com/perwendel/spark-kotlin
Apache License 2.0
9.64k stars 1.56k forks source link

Can't access uploaded file #952

Closed biswanath-app closed 5 years ago

biswanath-app commented 6 years ago

Hello, After uploading a file to the resource folder, I am not able to access that file. Every time when I am hitting that link it is showing 404 error. I checked the resource folder and the file is there but it is not accessible from the web. There is no permission issue. I can access the file once I restart the server.

Can anyone tell me how can I access that file without restarting the server?

Thanks

abhinavsayan commented 6 years ago

The file you are trying to access is a static file, these are listed when the server starts. I would recommend the following approach. Create a route to serve static files and then read and serve the specific file in the response.

get("/serve/static/:file", (req, res) -> {
    String file =  req.params(":file");

    byte[] bytes = Files.readAllBytes(Paths.get("upload_file_location/" + file));
    HttpServletResponse raw = res.raw();

    raw.setContentType("application/octet-stream");
        // the next line makes the file download; if you want it to open in the browser then comment it
    raw.setHeader("Content-Disposition", "filename=\"" + file +"\"");
    raw.getOutputStream().write(bytes);
    raw.getOutputStream().flush();
    raw.getOutputStream().close();

    return res.raw();
});

Hope this helps.