Same image is getting downloaded again and again. Downloading an image from Database in jsp?

南楼画角 提交于 2020-01-25 04:32:04

问题


I click the download button, and this servlet is called. After calling the image is downloaded, After that when I make the second call, the first image is getting downloaded again. So it keeps on giving me the image which I downloaded first. And not the image for which the mobile number I pass.

And here comes my servlet code in doGet:

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

来源:https://stackoverflow.com/questions/36355176/same-image-is-getting-downloaded-again-and-again-downloading-an-image-from-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!