如何下载名称存储在MySQl数据库中的文件?

时间:2019-04-11 06:02:36

标签: java mysql file jsp download

我希望下载我的上传文档,其文件名存储在Mysql数据库中,文件存储在upload_files文件夹中。每当执行代码时,我都会收到异常错误“ java.lang.IllegalStateException:此响应已调用getOutputStream()”。

表数据包含的文件名列为:

文件名varchar(100)NOT NULL

attachQr=attachQr+"year="+t_year+" and ";
String qry1 = "SELECT division,documenttitle,doc_id,authors,documenttype,remarks,year,filename FROM register_table where "+attachQr+"mssg='y'";
ResultSet rst= stmt.executeQuery(qry1);
%>
<table class="table table-bordered">
    <thead>
        <tr>                ----
            <th><font >Download</font></th>                         
            </tr>
        </thead>
            <%
                while(rst.next())
                    {
                     %>
                     <tbody>
                     <tr>
                         ----
                         <td><a href="file_download.jsp?filename=<%=rst.getString(8)%>">Download</a></td>
                     </tr>
                     </tbody>
                 <%
                         }                       %>                  
     </table>             
             <%                         }                  
       %>

file_download.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page import="java.io.*,java.util.*,java.sql.*" %>
<%
try{
    int i=0;
    String file_name="";
    if(request.getParameter("filename")!=null && request.getParameter("filename")!="")
        {
            file_name = request.getParameter("filename");
            System.out.println(file_name);
        }
    String connectionURL = "jdbc:mysql://localhost:3306/doc_search";
    String Content=new String("");
    Statement stmt=null;
    Connection con=null;
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    con=DriverManager.getConnection(connectionURL,"root","root");
    stmt=con.createStatement();
    String qry = "select * from  register_table where filename='"+file_name+"'";
    ResultSet rst= stmt.executeQuery(qry);
    if(rst.next())
    {
    Content=rst.getString("filename");
    }
    con.close();
    response.reset();       
    response.setContentType("APPLICATION/OCTET-STREAM");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + Content + "\"");
    java.io.FileInputStream fileInputStream =   new java.io.FileInputStream("F:\\JavaProject\\Doc_Search\\uploaded_files\\"+Content);

    while ((i=fileInputStream.read()) != -1) {
        response.getOutputStream().write(i);
    }       
    fileInputStream.close();
    out.close();
    response.getOutputStream().flush();
    response.getOutputStream().close();
    return;     
}
catch(Exception e){
    out.println(e);
}
%>

0 个答案:

没有答案