如何在JSP和Servlet中下载文件?

huangapple go评论70阅读模式
英文:

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.

&lt;a href=&quot;ServletName?value=filename.jpg&quot;&gt;Downlaod&lt;/a&gt;

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(&quot;value&quot;);
        //get the directory of the file.
        String path = getServletContext().getRealPath(&quot;/&quot; + &quot;files&quot; + File.separator + name);
        //set the content type
        response.setContentType(&quot;APPLICATION/OCTET-STREAM&quot;);
        //force to download dialog
        response.setHeader(&quot;Content-Disposition&quot;, &quot;attachment; filename=\&quot;&quot; + name + &quot;\&quot;&quot;);

        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.

huangapple
  • 本文由 发表于 2020年5月31日 03:28:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/62107691.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定