英文:
how to download file in jsp and servlet?
问题
我正在进行 JSP 项目的工作。我有一个选项可以下载文件或图像。但问题是,在下载文件后,它显示为不支持的文件格式。如何解决这个问题?
英文:
I am working on the jsp project. I have an option to download files or images. but the problem is after downloading the file it seems unsupported file format.how to solve that issue?
答案1
得分: 0
请查看下面的内容,这是您要翻译的部分:
首先,在您的JSP页面中创建一个简单的链接,将您重定向到Servlet。您可以替换jpg为任何类型的文件。
<a href="ServletName?value=filename.jpg">下载</a>
以下是用于从您的Web目录下载任何文件的Servlet代码。不要忘记在您的web-pages目录中创建一个“files”文件夹并粘贴文件。
try (PrintWriter out = response.getWriter()) {
//从URL中获取文件名
String name = request.getParameter("value");
//获取文件的目录
String path = getServletContext().getRealPath("/" + "files" + File.separator + name);
//设置内容类型
response.setContentType("APPLICATION/OCTET-STREAM");
//强制下载对话框
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();
}
就是这样了。您可以查看这个在JSP和Servlet中下载文件的YouTube视频获取更多信息。
英文:
First, create a simple link in your jsp page that redirects you to the servlet. instead of jpg, you can put any type of file.
<a href="ServletName?value=filename.jpg">Downlaod</a>
here is the servlet code for download any file from your web directory. Don't forget to create "files" folder in your web-pages directory and paste the file.
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();
}
that's all. you can check this Download File in jsp and servlet youtube video for more.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论