如何在 jsp 和 servlet 中下载文件?
how to download file in jsp and servlet?
我正在处理 jsp 项目。我可以选择下载文件或图像。但问题是下载文件后似乎不支持文件 format.how 来解决这个问题?
首先,在 jsp 页面中创建一个简单的 link,将您重定向到 servlet。除了jpg,你可以放任何类型的文件。
<a href="ServletName?value=filename.jpg">Downlaod</a>
这是从您的 Web 目录下载任何文件的 servlet 代码。不要忘记在您的网页目录中创建 "files" 文件夹并粘贴文件。
try (PrintWriter out = response.getWriter()) {
//fetch the file name from the url
String name = request.getParameter("value");
//get the directory of the file.
String path = getServletContext().getRealPath("/" + "files" + File.separator + name);
//set the content type
response.setContentType("APPLICATION/OCTET-STREAM");
//force to download dialog
response.setHeader("Content-Disposition", "attachment; filename=\"" + name + "\"");
FileInputStream ins = new FileInputStream(path);
int i;
while ((i = ins.read()) != -1) {
out.write(i);
}
ins.close();
out.close();
}
就是这样。你可以查看这个 Download File in jsp and servlet youtube 视频了解更多。
我正在处理 jsp 项目。我可以选择下载文件或图像。但问题是下载文件后似乎不支持文件 format.how 来解决这个问题?
首先,在 jsp 页面中创建一个简单的 link,将您重定向到 servlet。除了jpg,你可以放任何类型的文件。
<a href="ServletName?value=filename.jpg">Downlaod</a>
这是从您的 Web 目录下载任何文件的 servlet 代码。不要忘记在您的网页目录中创建 "files" 文件夹并粘贴文件。
try (PrintWriter out = response.getWriter()) {
//fetch the file name from the url
String name = request.getParameter("value");
//get the directory of the file.
String path = getServletContext().getRealPath("/" + "files" + File.separator + name);
//set the content type
response.setContentType("APPLICATION/OCTET-STREAM");
//force to download dialog
response.setHeader("Content-Disposition", "attachment; filename=\"" + name + "\"");
FileInputStream ins = new FileInputStream(path);
int i;
while ((i = ins.read()) != -1) {
out.write(i);
}
ins.close();
out.close();
}
就是这样。你可以查看这个 Download File in jsp and servlet youtube 视频了解更多。