How to download a file sent by a java backend to a React frontend

subDir99 :

I'm trying to download a certain file to a client using a React frontend and a Java backend. My situation is: in the frontend I'm showing a list of IDs that point to certain files. What I want to do is, in the frontend, send the request (with the id) to download that file and then the backend must search that file with that ID and send it to the client in order to be downloaded. I'm pretty new to this things so I don't know exactly how to start.

zappee :

You need to some job on frontend and backend part as well.

Frontend

Create a download link for each item, like this:

<a href='/download?id=1'>download</a>

Backend

You need to create a content download servlet or REST API. You can use this as an example and modify the code as you need:

@WebServlet("/download")
public class DownloadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Srting id = request.getParameter("id");

        resp.setContentType("text/plain");
        resp.setHeader("Content-disposition", "attachment; filename=sample.txt");

        try (OutputStream out = resp.getOutputStream()) {
            // search for data in your database
            out.write(...);
        }
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=299196&siteId=1