使用jsp下载以Blob格式存储在MySQL数据库中的PDF文件

时间:2019-02-16 21:01:24

标签: java html sql jsp

我正在尝试以Long Blob格式下载存储在MySQL数据库中的PDF文件。

<div class="container">
    <div id="loginHomeLogin" class="col-sm-6">
    <h2>Download file</h2>
    <form method="post"  action="downloadProject?id=${id}" enctype="multipart/form-data">
      Download:
        <input type="submit" value="Download" name="Download" id="download" />
    </form>
</div>

此处是通过按钮调用的java servelt页面(downloadProject)

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    ResultSet rs = null;
    PreparedStatement ps = null;
    Connection db = null;
    HttpSession session = request.getSession(true);

    OutputStream outx = null;
    InputStream filecontent = null;
    int BUFFER_SIZE = 4096; 
    try {
        PrintWriter out = response.getWriter();

        InitialContext ctx = new InitialContext();
        DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/webdb2");
        db = ds.getConnection();

        String id = request.getParameter("id");

        ps = db.prepareStatement("select * from tableName where id=?");
        ps.setInt(1,Integer.parseInt(id));
        rs=ps.executeQuery(); 


        while(rs.next()){

            Blob blob = rs.getBlob("fieldName");  
            InputStream inputStream = blob.getBinaryStream();
            int fileLength = inputStream.available();

            ServletContext context = getServletContext();

            // sets MIME type for the file download
            String mimeType = context.getMimeType(fileName);
            if (mimeType == null) {         
                mimeType = "application/octet-stream";
            }               

            response.setContentType(mimeType);
            response.setContentLength(fileLength);
            String headerKey = "Content-Disposition";
            String headerValue = String.format("attachment; filename=\"%s\"", fileName);
            response.setHeader(headerKey, headerValue);

            // writes the file to the client
            OutputStream outStream = response.getOutputStream();
            byte[] buffer = new byte[BUFFER_SIZE];
            int bytesRead = -1;

            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, bytesRead);
            }
            inputStream.close();
            outStream.close(); 

        }

        request.getSession(true).setAttribute("ins", "success");;
        response.sendRedirect("home");

    }

返回的错误是: java.lang.IllegalStateException:此响应已被调用getWriter(),带有页面的http错误500和下载的空白pdf。 错误在哪里?

0 个答案:

没有答案