List of usage examples for org.apache.commons.fileupload FileItemStream openStream
InputStream openStream() throws IOException;
From source file:ee.jaaaar.dreamestate.core.StreamingMultipartResolver.java
@Override public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException { // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(); upload.setFileSizeMax(maxUploadSize); String encoding = determineEncoding(request); Map<String, String[]> multipartParameters = new HashMap<String, String[]>(); MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<String, MultipartFile>(); // Parse the request try {//from ww w. j a v a2 s.c o m FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { String value = Streams.asString(stream, encoding); String[] curParam = (String[]) multipartParameters.get(name); if (curParam == null) { // simple form field multipartParameters.put(name, new String[] { value }); } else { // array of simple form fields String[] newParam = StringUtils.addStringToArray(curParam, value); multipartParameters.put(name, newParam); } } else { // Process the input stream MultipartFile file = new StreamingMultipartFile(item); multipartFiles.add(name, file); } } } catch (IOException e) { throw new MultipartException("something went wrong here", e); } catch (FileUploadException e) { throw new MultipartException("something went wrong here", e); } return new DefaultMultipartHttpServletRequest(request, multipartFiles, multipartParameters); }
From source file:is.hax.spring.web.multipart.StreamingMultipartResolver.java
public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException { // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(); upload.setFileSizeMax(maxUploadSize); String encoding = determineEncoding(request); Map<String, MultipartFile> multipartFiles = new HashMap<String, MultipartFile>(); Map<String, String[]> multipartParameters = new HashMap<String, String[]>(); // Parse the request try {//from w w w . j a va 2 s . c o m FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { String value = Streams.asString(stream, encoding); String[] curParam = multipartParameters.get(name); if (curParam == null) { // simple form field multipartParameters.put(name, new String[] { value }); } else { // array of simple form fields String[] newParam = StringUtils.addStringToArray(curParam, value); multipartParameters.put(name, newParam); } } else { // Process the input stream MultipartFile file = new StreamingMultipartFile(item); if (multipartFiles.put(name, file) != null) { throw new MultipartException("Multiple files for field name [" + file.getName() + "] found - not supported by MultipartResolver"); } } } } catch (IOException e) { throw new MultipartException("something went wrong here", e); } catch (FileUploadException e) { throw new MultipartException("something went wrong here", e); } return new DefaultMultipartHttpServletRequest(request, multipartFiles, multipartParameters); }
From source file:com.cubusmail.gwtui.server.services.AttachmentUploadServlet.java
@Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean isMultipart = ServletFileUpload.isMultipartContent(request); // Create a new file upload handler if (isMultipart) { ServletFileUpload upload = new ServletFileUpload(); try {/* w w w.j ava 2 s .c om*/ // Parse the request FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { System.out.println( "Form field " + name + " with value " + Streams.asString(stream) + " detected."); } else { System.out .println("File field " + name + " with file name " + item.getName() + " detected."); DataSource source = createDataSource(item); SessionManager.get().getCurrentComposeMessage().addComposeAttachment(source); } JSONObject jsonResponse = null; try { jsonResponse = new JSONObject(); jsonResponse.put("success", true); jsonResponse.put("error", "Upload successful"); } catch (Exception e) { } Writer w = new OutputStreamWriter(response.getOutputStream()); w.write(jsonResponse.toString()); w.close(); stream.close(); } } catch (Exception ex) { ex.printStackTrace(); } } response.setStatus(HttpServletResponse.SC_OK); }
From source file:io.lightlink.servlet.MultipartParameters.java
private void parseUpToNextStream() throws FileUploadException, IOException { while (fileItemIterator.hasNext()) { FileItemStream fItemStream = fileItemIterator.next(); String name = fItemStream.getFieldName(); if (fItemStream.isFormField()) { paramsMap.put(name, Streams.asString(fItemStream.openStream())); } else {//from w ww . j a v a 2s .com this.fileItemStream = fItemStream; break; // returns and waits while the the stream is consumed } } }
From source file:com.google.appinventor.server.UploadServlet.java
private InputStream getRequestStream(HttpServletRequest req, String expectedFieldName) throws Exception { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iterator = upload.getItemIterator(req); while (iterator.hasNext()) { FileItemStream item = iterator.next(); if (item.getFieldName().equals(expectedFieldName)) { return item.openStream(); }//from ww w . j a v a 2 s . c om } throw new IllegalArgumentException("Field " + expectedFieldName + " not found in upload"); }
From source file:com.webpagebytes.cms.controllers.ExportImportController.java
public void importContent(HttpServletRequest request, HttpServletResponse response, String requestUri) throws WPBException { File tempFile = null;//from w w w. j a v a 2 s .c o m try { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iterator = upload.getItemIterator(request); while (iterator.hasNext()) { FileItemStream item = iterator.next(); if (!item.isFormField() && item.getFieldName().equals("file")) { InputStream is = item.openStream(); tempFile = File.createTempFile("wpbImport", null); FileOutputStream fos = new FileOutputStream(tempFile); IOUtils.copy(is, fos); fos.close(); adminStorage.stopNotifications(); deleteAll(); // because the zip file entries cannot be predicted we needto import in two step1 // step 1 when we create the resource records // step 2 when we import the files, pages, modules and articles content InputStream is1 = new FileInputStream(tempFile); storageExporter.importFromZipStep1(is1); is1.close(); InputStream is2 = new FileInputStream(tempFile); storageExporter.importFromZipStep2(is2); is2.close(); org.json.JSONObject returnJson = new org.json.JSONObject(); returnJson.put(DATA, ""); httpServletToolbox.writeBodyResponseAsJson(response, returnJson, null); } } } catch (Exception e) { Map<String, String> errors = new HashMap<String, String>(); errors.put("", WPBErrors.WB_CANNOT_IMPORT_PROJECT); httpServletToolbox.writeBodyResponseAsJson(response, jsonObjectConverter.JSONObjectFromMap(null), errors); } finally { if (tempFile != null) { if (!tempFile.delete()) { tempFile.deleteOnExit(); } } adminStorage.startNotifications(); } }
From source file:com.pronoiahealth.olhie.server.rest.BooklogoUploadServiceImpl.java
@Override @POST/*from w ww. j a v a2 s . c o m*/ @Path("/upload") @Produces("text/html") @SecureAccess({ SecurityRoleEnum.ADMIN, SecurityRoleEnum.AUTHOR }) public String process(@Context HttpServletRequest req) throws ServletException, IOException, FileUploadException { try { // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(req); if (isMultipart == true) { // FileItemFactory fileItemFactory = new FileItemFactory(); String bookId = null; String contentType = null; // String data = null; byte[] bytes = null; String fileName = null; long size = 0; ServletFileUpload fileUpload = new ServletFileUpload(); fileUpload.setSizeMax(FILE_SIZE_LIMIT); FileItemIterator iter = fileUpload.getItemIterator(req); while (iter.hasNext()) { FileItemStream item = iter.next(); InputStream stream = item.openStream(); if (item.isFormField()) { // BookId if (item.getFieldName().equals("bookId")) { bookId = Streams.asString(stream); } } else { if (item != null) { contentType = item.getContentType(); fileName = item.getName(); item.openStream(); InputStream in = item.openStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(in, bos); bytes = bos.toByteArray(); // fileItem.get(); size = bytes.length; // data = Base64.encodeBytes(bytes); } } } // Add the logo Book book = bookDAO.getBookById(bookId); // Update the front cover BookCategory cat = holder.getCategoryByName(book.getCategory()); BookCover cover = holder.getCoverByName(book.getCoverName()); String authorName = bookDAO.getAuthorName(book.getAuthorId()); //String frontBookCoverEncoded = imgService // .createDefaultFrontCoverEncoded(book, cat, cover, // bytes, authorName); byte[] frontBookCoverBytes = imgService.createDefaultFrontCover(book, cat, cover, bytes, authorName); //String smallFrontBookCoverEncoded = imgService // .createDefaultSmallFrontCoverEncoded(book, cat, cover, // bytes, authorName); byte[] frontBookCoverSmallBytes = imgService.createDefaultSmallFrontCover(book, cat, cover, bytes, authorName); // Save it // Add the logo book = bookDAO.addLogoAndFrontCoverBytes(bookId, contentType, bytes, fileName, size, frontBookCoverBytes, frontBookCoverSmallBytes); } return "OK"; } catch (Exception e) { log.log(Level.SEVERE, "Throwing servlet exception for unhandled exception", e); // return "ERROR:\n" + e.getMessage(); if (e instanceof FileUploadException) { throw (FileUploadException) e; } else { throw new FileUploadException(e.getMessage()); } } }
From source file:com.qualogy.qafe.web.UploadService.java
public String uploadFile(HttpServletRequest request) { ServletFileUpload upload = new ServletFileUpload(); String errorMessage = ""; byte[] filecontent = null; String appUUID = null;// w w w . ja va 2 s . c o m String windowId = null; String filename = null; String mimeType = null; InputStream inputStream = null; ByteArrayOutputStream outputStream = null; try { FileItemIterator fileItemIterator = upload.getItemIterator(request); while (fileItemIterator.hasNext()) { FileItemStream item = fileItemIterator.next(); inputStream = item.openStream(); // Read the file into a byte array. outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[8192]; int len = 0; while (-1 != (len = inputStream.read(buffer))) { outputStream.write(buffer, 0, len); } if (filecontent == null) { filecontent = outputStream.toByteArray(); filename = item.getName(); mimeType = item.getContentType(); } if (item.getFieldName().indexOf(APP_UUID) > -1) { appUUID = item.getFieldName() .substring(item.getFieldName().indexOf(APP_UUID) + APP_UUID.length() + 1); } if (item.getFieldName().indexOf(APP_WINDOWID) > -1) { windowId = item.getFieldName() .substring(item.getFieldName().indexOf(APP_WINDOWID) + APP_WINDOWID.length() + 1); } } if ((appUUID != null) && (windowId != null)) { if (filecontent != null) { int maxFileSize = 0; if (ApplicationCluster.getInstance() .getConfigurationItem(Configuration.MAX_UPLOAD_FILESIZE) != null) { String maxUploadFileSzie = ApplicationCluster.getInstance() .getConfigurationItem(Configuration.MAX_UPLOAD_FILESIZE); if (StringUtils.isNumeric(maxUploadFileSzie)) { maxFileSize = Integer.parseInt(maxUploadFileSzie); } } if ((maxFileSize == 0) || (filecontent.length <= maxFileSize)) { Map<String, Object> fileData = new HashMap<String, Object>(); fileData.put(FILE_MIME_TYPE, mimeType); fileData.put(FILE_NAME, filename); fileData.put(FILE_CONTENT, filecontent); String uploadUUID = DataStore.KEY_LOOKUP_DATA + UniqueIdentifier.nextSeed().toString(); appUUID = concat(appUUID, windowId); ApplicationLocalStore.getInstance().store(appUUID, uploadUUID, fileData); return filename + "#" + UPLOAD_COMPLETE + "=" + uploadUUID; } else { errorMessage = "The maxmimum filesize in bytes is " + maxFileSize; } } } else { errorMessage = "Application UUID not specified"; } inputStream.close(); outputStream.close(); } catch (Exception e) { errorMessage = e.getMessage(); } return UPLOAD_ERROR + "=" + "File can not be uploaded: " + errorMessage; }
From source file:com.artgameweekend.projects.art.web.TagUploadServlet.java
@Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try {/*from www .j a va2s.c om*/ // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(); upload.setSizeMax(500000); res.setContentType(Constants.CONTENT_TYPE_TEXT); PrintWriter out = res.getWriter(); byte[] image = null; Tag tag = new Tag(); TagImage tagImage = new TagImage(); TagThumbnail tagThumbnail = new TagThumbnail(); String contentType = null; boolean bLandscape = false; try { FileItemIterator iterator = upload.getItemIterator(req); while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream in = item.openStream(); if (item.isFormField()) { out.println("Got a form field: " + item.getFieldName()); if (Constants.PARAMATER_NAME.equals(item.getFieldName())) { tag.setName(IOUtils.toString(in)); } if (Constants.PARAMATER_LAT.equals(item.getFieldName())) { tag.setLat(Double.parseDouble(IOUtils.toString(in))); } if (Constants.PARAMATER_LON.equals(item.getFieldName())) { tag.setLon(Double.parseDouble(IOUtils.toString(in))); } if (Constants.PARAMATER_LANDSCAPE.equals(item.getFieldName())) { bLandscape = IOUtils.toString(in).equals("on"); } } else { String fieldName = item.getFieldName(); String fileName = item.getName(); contentType = item.getContentType(); out.println("--------------"); out.println("fileName = " + fileName); out.println("field name = " + fieldName); out.println("contentType = " + contentType); try { image = IOUtils.toByteArray(in); } finally { IOUtils.closeQuietly(in); } } } } catch (SizeLimitExceededException e) { out.println("You exceeded the maximum size (" + e.getPermittedSize() + ") of the file (" + e.getActualSize() + ")"); } contentType = (contentType != null) ? contentType : "image/jpeg"; if (bLandscape) { image = rotate(image); } tagImage.setImage(image); tagImage.setContentType(contentType); tagThumbnail.setImage(createThumbnail(image)); tagThumbnail.setContentType(contentType); TagImageDAO daoImage = new TagImageDAO(); daoImage.create(tagImage); TagThumbnailDAO daoThumbnail = new TagThumbnailDAO(); daoThumbnail.create(tagThumbnail); TagDAO dao = new TagDAO(); tag.setKeyImage(tagImage.getKey()); tag.setKeyThumbnail(tagThumbnail.getKey()); tag.setDate(new Date().getTime()); dao.create(tag); } catch (Exception ex) { throw new ServletException(ex); } }
From source file:com.twosigma.beaker.core.module.elfinder.impl.commands.UploadCommand.java
@Override @SuppressWarnings("unchecked") public void execute(FsService fsService, HttpServletRequest request, ServletContext servletContext, JSONObject json) throws Exception { List<FileItemStream> listFiles = (List<FileItemStream>) request .getAttribute(FileItemStream.class.getName()); List<FsItemEx> added = new ArrayList<FsItemEx>(); String target = request.getParameter("target"); FsItemEx dir = super.findItem(fsService, target); FsItemFilter filter = FsItemFilterUtils.createFilterFromRequest(request); for (FileItemStream fis : listFiles) { java.nio.file.Path p = java.nio.file.Paths.get(fis.getName()); FsItemEx newFile = new FsItemEx(dir, p.getFileName().toString()); newFile.createFile();//w w w . j a v a2 s . co m InputStream is = fis.openStream(); newFile.writeStream(is); if (filter.accepts(newFile)) added.add(newFile); } json.put("added", files2JsonArray(request, added)); }