相同的图像一次又一次地下载。在jsp中从数据库下载图像?

时间:2016-04-01 11:27:21

标签: java mysql jsp servlets

我单击下载按钮,然后调用此servlet。在下载调用图像后,在我进行第二次调用之后,第一个图像再次被下载。所以它不断给我提供我先下载的图像。而不是我通过手机号码的图像。

这是我在doGet中的servlet代码:

 // connects to the database
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
conn = DriverManager.getConnection(dbURL, dbUser, dbPass);

// queries the database
String sql = "SELECT * FROM users WHERE mobileNumber = ?";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setInt(1, mobileNumber);

ResultSet result = statement.executeQuery();
if (result.next()) {
    // gets file name and file blob data
    String fileName = result.getString("file_name");
    Blob blob = result.getBlob("file_data");
    InputStream inputStream = blob.getBinaryStream();
    int fileLength = inputStream.available();

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

    ServletContext context = getServletContext();

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

    // set content properties and header attributes for the response
    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();              
} 
else {
    // no file found
    response.getWriter().print("File not found for the id: " + uploadId);   
}

0 个答案:

没有答案