I have a jsp / servlet web application in which the client can select the “course” and “destination” through the drop-down list, and then click the button to download all the files in the database that are listed in this course / destination combination. The servlet code does not quite work, because the zip file is not sent to the browser as an attachment. I have working code to upload one file at a time, but something is stuck with this code for zip files. All the files in the database are actually zip files, so I'm trying to pin a bunch of zip files. I did not think that this would require that they be handled otherwise than with any other file format. Can anyone see what is missing? Here is my doGet method code in a servlet that handles loading. Most of this code was found here on stackoverflow. Please note that the FileSubmitted object is my DOA, which contains all the file information for each file in the database, including Blob itself:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<FileSubmitted> fileList = new ArrayList<FileSubmitted>(); String course= request.getParameter("course"); String assignment = request.getParameter("assignment"); java.sql.PreparedStatement pstmt = null; java.sql.Connection conn = null; ResultSet rs; String queryString; try { conn = ConnectionManager.getConnection(); conn.setAutoCommit(false); queryString = "SELECT * FROM files WHERE courseID=\""+course+"\" AND assignmentID=\""+assignment+"\";"; pstmt = conn.prepareStatement(queryString); rs = pstmt.executeQuery(queryString); while(rs.next()) { fileList.add(new FileSubmitted(rs.getString("username"), rs.getString("courseID"), rs.getString("assignmentID"), rs.getString("fileName"), rs.getString("mimeType"), (Blob) rs.getBlob("contents"))); } response.setContentType("application/zip"); response.setHeader("Content-Disposition", "attachment; filename=\"allfiles.zip\""); ZipOutputStream output = null; byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; try { output = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE)); for (FileSubmitted file : fileList) { InputStream input = null; try { input = new BufferedInputStream(file.getContents().getBinaryStream(), DEFAULT_BUFFER_SIZE); output.putNextEntry(new ZipEntry(file.getFileName())); for (int length = 0; (length = input.read(buffer)) > 0;) { output.write(buffer, 0, length); } }//try catch (SQLException e) {e.printStackTrace();} finally{} output.closeEntry(); }//for }//try finally{} } catch (Exception e1) {e1.printStackTrace();} finally{} }
source share