Skip to content

Commit 3925638

Browse files
pauljervisEugen
authored andcommitted
add sample download file and article code (eugenp#4370)
1 parent 523fbf4 commit 3925638

2 files changed

Lines changed: 36 additions & 0 deletions

File tree

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package com.baeldung.servlets;
2+
3+
import java.io.IOException;
4+
import java.io.InputStream;
5+
import java.io.OutputStream;
6+
7+
import javax.servlet.ServletException;
8+
import javax.servlet.annotation.WebServlet;
9+
import javax.servlet.http.HttpServlet;
10+
import javax.servlet.http.HttpServletRequest;
11+
import javax.servlet.http.HttpServletResponse;
12+
13+
@WebServlet("/download")
14+
public class DownloadServlet extends HttpServlet {
15+
private final int ARBITARY_SIZE = 1048;
16+
17+
@Override
18+
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
19+
resp.setContentType("text/plain");
20+
resp.setHeader("Content-disposition", "attachment; filename=sample.txt");
21+
22+
OutputStream out = resp.getOutputStream();
23+
InputStream in = req.getServletContext().getResourceAsStream("/WEB-INF/sample.txt");
24+
25+
byte[] buffer = new byte[ARBITARY_SIZE];
26+
27+
int numBytesRead;
28+
while ((numBytesRead = in.read(buffer)) > 0) {
29+
out.write(buffer, 0, numBytesRead);
30+
}
31+
32+
in.close();
33+
out.flush();
34+
}
35+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
nice simple text file

0 commit comments

Comments
 (0)