fileLength = 0尝试从数据库下载PDF文件时

时间:2016-02-01 10:01:14

标签: java oracle file servlets

fileLength = 0 文件阅读成功
尝试从DATABASE下载pdf文件时,将文件长度设置为null。     实际上必须得到一些PDF文件,其中有一些内容存储在本地数据库中     请你帮我解决这个问题,现在应该做些什么来解决这个问题,文件只通过客户端程序上传

        public class FileDownload extends HttpServlet {

          private static final int  BUFFER_SIZE = 40960;


        protected void doGet(--){

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


            Connection conn=null;
            try {

                 Class.forName("--");

                Connection con=DriverManager.getConnection("--");

                String sql="SELECT * from book where bookId=?";
                PreparedStatement statement = con.prepareStatement(sql);
                statement.setString(1, bookId);

                ResultSet result = statement.executeQuery();

                        if(result.next()) {

                    String bookTitle = result.getString("bookTitle");
                    Blob blob = result.getBlob("bookContent");


                    InputStream inputStream = blob.getBinaryStream();
                    int fileLength = inputStream.available();
                    System.out.println("fileLength = " +fileLength);

                    ServletContext context = getServletContext();
                    String mimeType = context.getMimeType(bookTitle);
                    if (mimeType == null) {        
                        mimeType = "application/pdf";
                                       }              

                    System.out.println("File Reading Success");
                    response.setContentType(mimeType);

                    response.setContentLength(fileLength);
                    String headerKey = "Content-Disposition";
                    String headerValue = String.format("attachment; fileName=\"%s\"", bookTitle +".pdf");

                    response.setHeader(headerKey, headerValue);


                    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();             
                } 

1 个答案:

答案 0 :(得分:1)

InputStream.available()不返回文件长度,而是返回可以不受阻塞地从流中读取的字节数。在您明确请求内容之前,数据库很可能不会发送Blob的任何字节,因此返回0。

因此请使用

int fileLength = blob.length();

,它为您提供文件的确切长度。