List of usage examples for org.apache.commons.fileupload FileItem getInputStream
InputStream getInputStream() throws IOException;
From source file:com.ephesoft.gxt.admin.server.ImportDocumentTypeUploadServlet.java
/** * This API is used to write content in temp file. * //from w ww .j a v a 2 s. c om * @param item {@link FileItem} uploaded file item. * @param filePath {@link String} to create temporary file. * @param printWriter {@link PrintWriter}. * @return {@link File} temporary file. */ private File copyItemContentInFile(final FileItem item, final String filePath, final PrintWriter printWriter) { File tempZipFile = null; OutputStream out = null; InputStream instream = null; try { instream = item.getInputStream(); tempZipFile = new File(filePath); if (tempZipFile.exists()) { tempZipFile.delete(); } out = new FileOutputStream(tempZipFile); final byte buf[] = new byte[1024]; int len; while ((len = instream.read(buf)) > 0) { out.write(buf, 0, len); } } catch (final FileNotFoundException e) { printWriter.write("Unable to create the export folder.Please try again."); } catch (final IOException e) { printWriter.write("Unable to read the file.Please try again."); } finally { if (out != null) { try { out.close(); } catch (final IOException ioe) { log.error("Could not close stream for file." + tempZipFile); } } if (instream != null) { try { instream.close(); } catch (final IOException ioe) { log.error("Could not close stream for file." + filePath); } } } return tempZipFile; }
From source file:es.ucm.fdi.dalgs.degree.service.DegreeService.java
@PreAuthorize("hasRole('ROLE_ADMIN')") @Transactional(readOnly = false)// w w w . j ava2 s.co m public ResultClass<Boolean> uploadCSV(UploadForm upload, Locale locale) { ResultClass<Boolean> result = new ResultClass<>(); if (!upload.getFileData().isEmpty()) { CsvPreference prefers = new CsvPreference.Builder(upload.getQuoteChar().charAt(0), upload.getDelimiterChar().charAt(0), upload.getEndOfLineSymbols()).build(); List<Degree> list = null; try { FileItem fileItem = upload.getFileData().getFileItem(); DegreeCSV degreeUpload = new DegreeCSV(); list = degreeUpload.readCSVDegreeToBean(fileItem.getInputStream(), upload.getCharset(), prefers); if (list == null) { result.setHasErrors(true); result.getErrorsList().add(messageSource.getMessage("error.params", null, locale)); } else { result.setSingleElement(repositoryDegree.persistListDegrees(list)); if (result.getSingleElement()) { for (Degree c : list) { Degree aux = repositoryDegree.existByCode(c.getInfo().getCode()); result.setSingleElement(result.getSingleElement() && manageAclService.addACLToObject(aux.getId(), aux.getClass().getName())); } } } } catch (IOException e) { e.printStackTrace(); result.setSingleElement(false); } } else { result.setHasErrors(true); result.getErrorsList().add(messageSource.getMessage("error.fileEmpty", null, locale)); } return result; }
From source file:com.silverpeas.thumbnail.control.ThumbnailController.java
public static boolean processThumbnail(ForeignPK pk, String objectType, List<FileItem> parameters) throws Exception { boolean thumbnailChanged = false; String mimeType = null;//ww w .j a v a2s .c o m String physicalName = null; FileItem uploadedFile = FileUploadUtil.getFile(parameters, "WAIMGVAR0"); if (uploadedFile != null) { String logicalName = uploadedFile.getName().replace('\\', '/'); if (StringUtil.isDefined(logicalName)) { logicalName = FilenameUtils.getName(logicalName); mimeType = FileUtil.getMimeType(logicalName); String type = FileRepositoryManager.getFileExtension(logicalName); if (FileUtil.isImage(logicalName)) { physicalName = String.valueOf(System.currentTimeMillis()) + '.' + type; SilverpeasFileDescriptor descriptor = new SilverpeasFileDescriptor(pk.getInstanceId()) .mimeType(mimeType).parentDirectory(publicationSettings.getString("imagesSubDirectory")) .fileName(physicalName); SilverpeasFile target = SilverpeasFileProvider.newFile(descriptor); target.writeFrom(uploadedFile.getInputStream()); } else { throw new ThumbnailRuntimeException("ThumbnailController.processThumbnail()", SilverpeasRuntimeException.ERROR, "thumbnail_EX_MSG_WRONG_TYPE_ERROR"); } } } // If no image have been uploaded, check if one have been picked up from a gallery if (physicalName == null) { // on a pas d'image, regarder s'il y a une provenant de la galerie String nameImageFromGallery = FileUploadUtil.getParameter(parameters, "valueImageGallery"); if (StringUtil.isDefined(nameImageFromGallery)) { physicalName = nameImageFromGallery; mimeType = "image/jpeg"; } } // If one image is defined, save it through Thumbnail service if (StringUtil.isDefined(physicalName)) { ThumbnailDetail detail = new ThumbnailDetail(pk.getInstanceId(), Integer.parseInt(pk.getId()), ThumbnailDetail.THUMBNAIL_OBJECTTYPE_PUBLICATION_VIGNETTE); detail.setOriginalFileName(physicalName); detail.setMimeType(mimeType); try { ThumbnailController.updateThumbnail(detail); thumbnailChanged = true; } catch (ThumbnailRuntimeException e) { SilverTrace.error("thumbnail", "KmeliaRequestRouter.processVignette", "thumbnail_MSG_UPDATE_THUMBNAIL_KO", e); try { ThumbnailController.deleteThumbnail(detail); } catch (Exception exp) { SilverTrace.info("thumbnail", "KmeliaRequestRouter.processVignette", "thumbnail_MSG_DELETE_THUMBNAIL_KO", exp); } } } return thumbnailChanged; }
From source file:com.exedio.cope.live.MediaServlet.java
void doRequest(final HttpServletRequest request, final HttpServletResponse response, final Anchor anchor) { final String featureID = request.getParameter(FEATURE); if (featureID == null) throw new NullPointerException(); final Media feature = (Media) model.getFeature(featureID); if (feature == null) throw new NullPointerException(featureID); final String itemID = request.getParameter(ITEM); if (itemID == null) throw new NullPointerException(); final Item item; try {/*from w w w . j a va 2 s . co m*/ startTransaction("media(" + featureID + ',' + itemID + ')'); item = model.getItem(itemID); model.commit(); } catch (final NoSuchIDException e) { throw new RuntimeException(e); } finally { model.rollbackIfNotCommitted(); } final FileItem fi = anchor.getModification(feature, item); if (fi == null) throw new NullPointerException(featureID + '-' + itemID); response.setContentType(fi.getContentType()); response.setContentLength((int) fi.getSize()); InputStream in = null; ServletOutputStream out = null; try { in = fi.getInputStream(); out = response.getOutputStream(); final byte[] b = new byte[20 * 1024]; for (int len = in.read(b); len >= 0; len = in.read(b)) out.write(b, 0, len); } catch (final IOException e) { throw new RuntimeException(e); } finally { if (in != null) { try { in.close(); } catch (final IOException e) { e.printStackTrace(); } } if (out != null) { try { out.close(); } catch (final IOException e) { e.printStackTrace(); } } } }
From source file:com.tasktop.c2c.server.tasks.web.service.AttachmentUploadController.java
@RequestMapping(value = "", method = RequestMethod.POST) public void upload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, TextHtmlContentExceptionWrapper { try {//w w w . j a va2 s . c om FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<Attachment> attachments = new ArrayList<Attachment>(); Map<String, String> formValues = new HashMap<String, String>(); try { List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { formValues.put(item.getFieldName(), item.getString()); } else { Attachment attachment = new Attachment(); attachment.setAttachmentData(readInputStream(item.getInputStream())); attachment.setFilename(item.getName()); attachment.setMimeType(item.getContentType()); attachments.add(attachment); } } } catch (FileUploadException e) { e.printStackTrace(); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); // FIXME better code return; } for (int i = 0; i < attachments.size(); i++) { String description = formValues .get(AttachmentUploadUtil.ATTACHMENT_DESCRIPTION_FORM_NAME_PREFIX + i); if (description == null) { throw new IllegalArgumentException( "Missing description " + i + 1 + " of " + attachments.size()); } attachments.get(0).setDescription(description); } TaskHandle taskHandle = getTaskHandle(formValues); UploadResult result = doUpload(response, attachments, taskHandle); response.setContentType("text/html"); response.getWriter() .write(jsonMapper.writeValueAsString(Collections.singletonMap("uploadResult", result))); } catch (Exception e) { throw new TextHtmlContentExceptionWrapper(e.getMessage(), e); } }
From source file:edu.umd.cs.submitServer.servlets.UploadProjectStarterFiles.java
/** * The doPost method of the servlet. <br> * /*from w w w. j a va 2s . c om*/ * This method is called when a form has its tag value method equals to * post. * * @param request * the request send by the client to the server * @param response * the response send by the server to the client * @throws ServletException * if an error occurred * @throws IOException * if an error occurred */ @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { MultipartRequest multipartRequest = (MultipartRequest) request.getAttribute(MULTIPART_REQUEST); Project project = (Project) request.getAttribute(PROJECT); Connection conn = null; FileItem fileItem = null; try { conn = getConnection(); fileItem = multipartRequest.getFileItem(); long sizeInBytes = fileItem.getSize(); if (sizeInBytes == 0) { throw new ServletException("Trying upload file of size 0"); } // copy the fileItem into a byte array InputStream is = fileItem.getInputStream(); ByteArrayOutputStream bytes = new ByteArrayOutputStream((int) sizeInBytes); IO.copyStream(is, bytes); byte[] bytesForUpload = bytes.toByteArray(); // set the byte array as the archive project.setArchiveForUpload(bytesForUpload); FormatDescription desc = FormatIdentification.identify(bytesForUpload); if (desc == null || !desc.getMimeType().equals("application/zip")) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "You MUST submit starter files that are either zipped or jarred"); return; } Integer archivePK = project.getArchivePK(); if (archivePK == null || archivePK.equals(0)) { // If there is no archive, then upload and create a new one project.uploadCachedArchive(conn); project.update(conn); } else { // Otherwise, update the archive we already have project.updateCachedArchive(bytesForUpload, conn); } String redirectUrl = request.getContextPath() + "/view/instructor/projectUtilities.jsp?projectPK=" + project.getProjectPK(); response.sendRedirect(redirectUrl); } catch (SQLException e) { throw new ServletException(e); } finally { releaseConnection(conn); } }
From source file:es.ucm.fdi.dalgs.module.service.ModuleService.java
@PreAuthorize("hasRole('ROLE_ADMIN')") @Transactional(readOnly = false)/* w ww . j av a 2 s . c o m*/ public ResultClass<Boolean> uploadCSV(UploadForm upload, Long id_degree, Locale locale) { ResultClass<Boolean> result = new ResultClass<>(); if (!upload.getFileData().isEmpty()) { CsvPreference prefers = new CsvPreference.Builder(upload.getQuoteChar().charAt(0), upload.getDelimiterChar().charAt(0), upload.getEndOfLineSymbols()).build(); List<Module> list = null; try { FileItem fileItem = upload.getFileData().getFileItem(); ModuleCSV moduleUpload = new ModuleCSV(); Degree d = serviceDegree.getDegree(id_degree).getSingleElement(); list = moduleUpload.readCSVModuleToBean(fileItem.getInputStream(), upload.getCharset(), prefers, d); if (list == null) { result.setHasErrors(true); result.getErrorsList().add(messageSource.getMessage("error.params", null, locale)); } else { result.setSingleElement(repositoryModule.persistListModules(list)); if (result.getSingleElement()) { for (Module c : list) { Module aux = repositoryModule.existByCode(c.getInfo().getCode(), id_degree); result.setSingleElement(result.getSingleElement() && manageAclService.addACLToObject(aux.getId(), aux.getClass().getName())); } } } } catch (IOException e) { e.printStackTrace(); result.setSingleElement(false); } } else { result.setHasErrors(true); result.getErrorsList().add(messageSource.getMessage("error.fileEmpty", null, locale)); } return result; }
From source file:com.sketchy.server.UpgradeUploadServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { JSONServletResult jsonServletResult = new JSONServletResult(Status.SUCCESS); try {//ww w . j a va 2 s . com boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(FileUtils.getTempDirectory()); factory.setSizeThreshold(MAX_SIZE); ServletFileUpload servletFileUpload = new ServletFileUpload(factory); List<FileItem> files = servletFileUpload.parseRequest(request); String version = ""; for (FileItem fileItem : files) { String uploadFileName = fileItem.getName(); if (StringUtils.isNotBlank(uploadFileName)) { JarInputStream jarInputStream = null; try { // check to make sure it's a Sketchy File with a Manifest File jarInputStream = new JarInputStream(fileItem.getInputStream(), true); Manifest manifest = jarInputStream.getManifest(); if (manifest == null) { throw new Exception("Invalid Upgrade File!"); } Attributes titleAttributes = manifest.getMainAttributes(); if ((titleAttributes == null) || (!StringUtils.containsIgnoreCase( titleAttributes.getValue("Implementation-Title"), "Sketchy"))) { throw new Exception("Invalid Upgrade File!"); } version = titleAttributes.getValue("Implementation-Version"); } catch (Exception e) { throw new Exception("Invalid Upgrade File!"); } finally { IOUtils.closeQuietly(jarInputStream); } // save new .jar file as "ready" fileItem.write(new File("Sketchy.jar.ready")); jsonServletResult.put("version", version); } } } } catch (Exception e) { jsonServletResult = new JSONServletResult(Status.ERROR, e.getMessage()); } response.setContentType("text/html"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().print(jsonServletResult.toJSONString()); }
From source file:mercury.DigitalMediaDAO.java
public final Integer uploadToDigitalMedia(FileItem file) { Connection con = null;/*from w w w . j a v a 2 s. c om*/ Integer serial = 0; String filename = file.getName(); if (filename.lastIndexOf('\\') != -1) { filename = filename.substring(filename.lastIndexOf('\\') + 1); } if (filename.lastIndexOf('/') != -1) { filename = filename.substring(filename.lastIndexOf('/') + 1); } try { InputStream is = file.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); serial = getNextSerial("digital_media_id_seq"); if (serial != 0) { con = getDataSource().getConnection(); con.setAutoCommit(false); String sql = " INSERT INTO digital_media " + " (id, file, mime_type, file_name) " + " VALUES (?, ?, ?, ?) "; PreparedStatement pstm = con.prepareStatement(sql); pstm.setInt(1, serial); pstm.setBinaryStream(2, bis, (int) file.getSize()); pstm.setString(3, file.getContentType()); pstm.setString(4, filename); pstm.executeUpdate(); pstm.close(); is.close(); con.commit(); } } catch (Exception e) { log.error(e.getMessage(), e); throw new DAOException(e.getMessage()); } finally { closeConnection(con); } return serial; }
From source file:com.fdt.sdl.admin.ui.action.UploadAction.java
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { if (!SecurityUtil.isAdminUser(request)) return (mapping.findForward("welcome")); ActionMessages messages = new ActionMessages(); ActionMessages errors = new ActionMessages(); if (FileUpload.isMultipartContent(request)) { try {//ww w . java2 s.c o m //read old dataset values ServerConfiguration sc = ServerConfiguration.getServerConfiguration(); ArrayList<DatasetConfiguration> old_dcs = ServerConfiguration.getDatasetConfigurations(); Map<String, Long> oldModifiedTimes = new HashMap<String, Long>(old_dcs.size()); for (DatasetConfiguration old_dc : old_dcs) { oldModifiedTimes.put(old_dc.getName(), old_dc.getConfigFile().lastModified()); } DiskFileUpload upload = new DiskFileUpload(); upload.setSizeMax(10 * 1024 * 1024); List items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { } else { String fileName = (new File(item.getName())).getName(); if (fileName.endsWith(".zip")) { try { extractZip(item.getInputStream()); } catch (Exception ee) { logger.error("exception for zip:" + ee); ee.printStackTrace(); } } } } messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("action.uploadFiles.success")); saveMessages(request, messages); //merge old values into the new data set if (sc.getIsMergingOldDatasetValues()) { ArrayList<DatasetConfiguration> new_dcs = ServerConfiguration.getDatasetConfigurations(); for (DatasetConfiguration new_dc : new_dcs) { if (oldModifiedTimes.get(new_dc.getName()) != null && new_dc.getConfigFile().lastModified() > oldModifiedTimes.get(new_dc.getName())) { for (DatasetConfiguration old_dc : old_dcs) { if (new_dc.getName() == old_dc.getName()) { new_dc.merge(old_dc); new_dc.save(); break; } } } } } if (sc.getAllowedLicenseLevel() > 0) { //reload from the disk ArrayList<DatasetConfiguration> dcs = ServerConfiguration.getDatasetConfigurations(); for (DatasetConfiguration dc : dcs) { try { SchedulerTool.scheduleIndexingJob(dc); } catch (Throwable t) { logger.info("Failed to schedule for " + dc.getName() + ": " + t.toString()); } } } return mapping.findForward("continue"); } catch (Exception e) { errors.add("error", new ActionMessage("action.uploadFiles.error")); saveErrors(request, errors); return mapping.findForward("continue"); } } else { // from other page // } return mapping.findForward("continue"); }