/** * Adds a single file into the ZipOutputStream with specified entry name. * * @throws IOException */ private void addFileToZip(ZipOutputStream zipOut, ReshakaUploadedFile file, String name) throws IOException { if (log.isTraceEnabled()) { log.trace(">> addFileToZip(): " + file); } ZipEntry entry = new ZipEntry(name); zipOut.putNextEntry(entry); try (InputStream in = file.getInputstream()) { FileUtils.copyStream(file.getInputstream(), zipOut); zipOut.closeEntry(); } if (log.isTraceEnabled()) { log.trace("<< addFileToZip()"); } }
private Attachment prepareAttachment(User user, List<ReshakaUploadedFile> files, String tags) { if (files.isEmpty()) { if (log.isDebugEnabled()) { log.debug("prepareAttachment() : List of files is empty! Nothing to compress."); } return null; } if (files.size() == 1) { if (log.isTraceEnabled()) { log.trace( "prepareAttachment() : Single file is being uploaded. Delegating to uploadFile()"); } try { return prepareAttachment( files.get(0).getFileName(), files.get(0).getContentType(), user, files.get(0).getContents(), tags); } catch (IOException ex) { if (log.isTraceEnabled()) { log.trace("prepareAttachment() : I/O exception" + ex); } return null; } } try { // create zip file log.trace("prepareAttachment(): Creating zip-file"); File root = new File(DEFAULT_UPLOAD_DIRECTORY, user.getLogin()); root.mkdirs(); File file = File.createTempFile("upload_", ".zip", root); try (ZipOutputStream zos = new ZipOutputStream(file)) { zos.setEncoding("utf-8"); zos.setMethod(ZipOutputStream.DEFLATED); zos.setLevel(Deflater.BEST_COMPRESSION); for (ReshakaUploadedFile uf : files) { addFileToZip(zos, uf, uf.getFileName()); } } if (log.isDebugEnabled()) { log.debug("prepareAttachment(): Files are saved at " + file); } if (file.length() > MAX_ZIP_SIZE) { file.delete(); throw new IOException("File too large."); } // Create attachment Attachment att = new Attachment(); att.setName(file.getName()); att.setMimeType("application/zip"); att.setSize(file.length()); att.setMD5(FileUtils.getMD5(file)); att.setFileName(user.getLogin() + "/" + file.getName()); if (log.isTraceEnabled()) { log.trace("<< prepareAttachment()"); } return att; } catch (IOException ex) { log.error("prepareAttachment(): Failed to upload files. ", ex); return null; } }