从数据库表下载文件(Mysql,spring)

时间:2012-01-20 09:55:25

标签: java mysql spring

我已经编写了一个用于下载文件的代码(数据库表中的blob)。我在下载时得到提示但是当我下载它的大小增加并打开作为空白文件或损坏的文件。控制器调用2个服务方法downloadfile( ): - 将blob类型转换为字节数组。

downloadfilename(): - 获取存储在数据库中的文件名。 控制器代码

  protected ModelAndView handleRequestInternal(HttpServletRequest request,
                HttpServletResponse response) throws Exception {
            byte[] fileBytes = userService.downloadFile();
            String filename = userService.downloadFileName();

            String fileType = filename.substring(filename.indexOf(".")+1,filename.length());
            System.out.println("FILETYPE IS :>>>>>>>>>>>>>>>"+fileType);

            if (fileType.trim().equalsIgnoreCase("txt"))
            {
            response.setContentType( "text/plain" );
            }
            else if (fileType.trim().equalsIgnoreCase("doc"))
            {
            response.setContentType( "application/msword" );
            }
            else if (fileType.trim().equalsIgnoreCase("xls"))
            {
            response.setContentType( "application/vnd.ms-excel" );
            }
            else if (fileType.trim().equalsIgnoreCase("pdf"))
            {
            response.setContentType( "application/pdf" );
            }
            else if (fileType.trim().equalsIgnoreCase("ppt"))
            {
            response.setContentType( "application/ppt" );
            }
            else
            {
            response.setContentType( "application/octet-stream" );
            }

            response.setHeader("Content-Disposition","attachment; filename=\""+filename+"\"");
            response.setHeader("cache-control", "no-cache");
            response.setHeader("cache-control", "must-revalidate");

            ServletOutputStream outs = response.getOutputStream();
            outs.write(fileBytes);
            outs.flush();
            outs.close();
            return null;

        }

DAO CLASS就是这样......

public String downloadFile(){
String selectquery = "select * from upload_file where id=1";
                System.out.println("inside after query");
                ResultSet rs = stmt.executeQuery(selectquery);
                while (rs.next()) {
                    fileBytes = rs.getBytes("description");
                    fileName = rs.getString("upload_filename");
                    System.out.println("**************************************"
                            + fileName);    
                }
                return fileName;
            } catch (SQLException s) {
                System.out.println(s);
            }
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

1 个答案:

答案 0 :(得分:0)

你的问题不是很清楚,但我想我知道你的意思。

如果文件很大(10MB),则必须在http标头中指定内容长度。如果不是,浏览器将表现为stange。 (精确限制10MB是浏览器所依赖的)