Внедрение простого сервлета загрузки файлов
Как я могу реализовать простой сервлет загрузки файлов?
Идея состоит в том, что с запросом GET index.jsp?filename=file.txt
пользователь может загрузить, например. file.txt
из сервлета файла, и сервлет файла загрузит этот файл пользователю.
Я могу получить файл, но как я могу реализовать загрузку файла?
Ответы
Ответ 1
Это зависит. Если указанный файл общедоступен через ваш HTTP-сервер или контейнер сервлета, вы можете просто перенаправить его через response.sendRedirect()
.
Если это не так, вам нужно вручную скопировать его в выходной поток ответа:
OutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(my_file);
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.flush();
Конечно, вам нужно будет обрабатывать соответствующие исключения.
Ответ 2
Предполагая, что у вас есть доступ к сервлету ниже
http://localhost:8080/myapp/download?id=7
Мне нужно создать сервлет и зарегистрировать его в web.xml
web.xml
<servlet>
<servlet-name>DownloadServlet</servlet-name>
<servlet-class>com.myapp.servlet.DownloadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DownloadServlet</servlet-name>
<url-pattern>/download</url-pattern>
</servlet-mapping>
DownloadServlet.java
public class DownloadServlet extends HttpServlet {
protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
String fileName = "";
String fileType = "";
// Find this file id in database to get file name, and file type
// You must tell the browser the file type you are going to send
// for example application/pdf, text/plain, text/html, image/jpg
response.setContentType(fileType);
// Make sure to show the download dialog
response.setHeader("Content-disposition","attachment; filename=yourcustomfilename.pdf");
// Assume file name is retrieved from database
// For example D:\\file\\test.pdf
File my_file = new File(fileName);
// This should send the file to browser
OutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(my_file);
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.flush();
}
}
Ответ 3
Попробуйте с ресурсом
File file = new File("Foo.txt");
try (PrintStream ps = new PrintStream(file)) {
ps.println("Bar");
}
response.setContentType("application/octet-stream");
response.setContentLength((int) file.length());
response.setHeader( "Content-Disposition",
String.format("attachment; filename=\"%s\"", file.getName()));
OutputStream out = response.getOutputStream();
try (FileInputStream in = new FileInputStream(file)) {
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
}
out.flush();
Ответ 4
Самый простой способ реализовать загрузку - это то, что вы направляете пользователей в местоположение файла, браузеры автоматически сделают это для вас.
Вы можете легко достичь этого через:
HttpServletResponse.sendRedirect()
Ответ 5
что такое вложение% s in------; имя файла =\"% s \"