context.getMimeType()返回null,inputStream.available()在servlet中返回0

时间:2014-07-06 12:34:33

标签: java database servlets download

ResultSet result = statement.executeQuery();

        if (result.next()) {
            // gets file name and file blob data
            String fileName = result.getString("Name");

            Blob blob = result.getBlob(3);

            InputStream inputStream = blob.getBinaryStream();

            int fileLength = inputStream.available();

      //      out.println("fileLength = " + fileLength);


            ServletContext context = getServletContext();

            // sets MIME type for the file download

            String mimeType = context.getMimeType(fileName);
       //     String mimeType = "image/jpeg";


            if (mimeType == null) {        
                mimeType = "application/octet-stream";
            }    

我正在尝试从数据库下载数据。我正在使用Oracle。我在这做错了什么?

context.getMimeType始终返回null,inputStream.available()始终返回0.

我查看了其他答案,但它们与我无关。请帮忙。

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。其内容如下:)

我意识到没有必要获取mime,因为我只需要代码来运行图像文件。

 if (result.next()) {
                 // gets file name and file blob data
                String fileID = result.getString("image_id");
                Blob blob = result.getBlob(3);
                InputStream inputStream = blob.getBinaryStream();
                int length = (int)blob.length();
                ServletContext context = getServletContext();

                 // set content properties and header attributes for the response
                response.setContentType("image/jpeg");
                response.setContentLength(length);
                String headerKey = "Content-Disposition";
                String headerValue = String.format("attachment; filename=\"%s\"", fileID);
                 response.setHeader(headerKey, headerValue);

                 // writes the file to the client
                 OutputStream outStream = response.getOutputStream();
                 ServletOutputStream output = response.getOutputStream();
                 BufferedOutputStream bos = new BufferedOutputStream(output);
                 byte[] arr1 = blob.getBytes(1, length);
                 bos.write(arr1);

                inputStream.close();
                outStream.close();             
        }