List of usage examples for org.apache.commons.fileupload FileItemStream getName
String getName();
From source file:hrpod.web.Upload.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w ww . j a v a 2s . co m*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setHeader("Content-Type", "application/json"); response.setCharacterEncoding("utf8"); response.setContentType("application/json"); try (PrintWriter out = response.getWriter()) { try { String uploadType = request.getParameter("type"); IngestDataBL ingest = new IngestDataBL(); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iterator = upload.getItemIterator(request); while (iterator.hasNext()) { FileItemStream item = iterator.next(); if (item.getName() != null) { if (uploadType.equals("resumes")) { ingest.doIngetsJobs(item.openStream()); } else if (uploadType.equals("jobs")) { ingest.doIngetsJobs(item.openStream()); } } } out.write("SUCCESS"); } catch (Exception e) { e.printStackTrace(); } } }
From source file:jhi.buntata.server.DatasourceIcon.java
@Put public void putImage(Representation entity) { if (entity != null && MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) { try {/* ww w .j a v a2 s . c o m*/ DiskFileItemFactory factory = new DiskFileItemFactory(); RestletFileUpload upload = new RestletFileUpload(factory); FileItemIterator fileIterator = upload.getItemIterator(entity); if (fileIterator.hasNext()) { FileItemStream fi = fileIterator.next(); String name = fi.getName(); File file = new File(dataDir, name); int i = 1; while (file.exists()) file = new File(dataDir, (i++) + name); Files.copy(fi.openStream(), file.toPath()); BuntataDatasource ds = dao.get(id); ds.setIcon(file.getName()); dao.updateIcon(ds); } } catch (Exception e) { e.printStackTrace(); } } else { throw new ResourceException(Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE); } }
From source file:com.example.getstarted.util.CloudStorageHelper.java
/** * Uploads a file to Google Cloud Storage to the bucket specified in the BUCKET_NAME * environment variable, appending a timestamp to end of the uploaded filename. *///from www . j a v a 2 s . c o m public String uploadFile(FileItemStream fileStream, final String bucketName) throws IOException, ServletException { checkFileExtension(fileStream.getName()); DateTimeFormatter dtf = DateTimeFormat.forPattern("-YYYY-MM-dd-HHmmssSSS"); DateTime dt = DateTime.now(DateTimeZone.UTC); String dtString = dt.toString(dtf); final String fileName = fileStream.getName() + dtString; // the inputstream is closed by default, so we don't need to close it here BlobInfo blobInfo = storage.create(BlobInfo.newBuilder(bucketName, fileName) // Modify access list to allow all users with link to read file .setAcl(new ArrayList<>(Arrays.asList(Acl.of(User.ofAllUsers(), Role.READER)))).build(), fileStream.openStream()); logger.log(Level.INFO, "Uploaded file {0} as {1}", new Object[] { fileStream.getName(), fileName }); // return the public download link return blobInfo.getMediaLink(); }
From source file:jhi.buntata.server.NodeMedia.java
@Put public boolean putMedia(Representation entity) { if (entity != null && MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) { try {//from w ww. ja v a 2 s . co m BuntataNode node = nodeDAO.get(id); DiskFileItemFactory factory = new DiskFileItemFactory(); RestletFileUpload upload = new RestletFileUpload(factory); FileItemIterator fileIterator = upload.getItemIterator(entity); if (fileIterator.hasNext()) { String nodeName = node.getName().replace(" ", "-"); File dir = new File(dataDir, nodeName); dir.mkdirs(); FileItemStream fi = fileIterator.next(); String name = fi.getName(); File file = new File(dir, name); int i = 1; while (file.exists()) file = new File(dir, (i++) + name); // Copy the file to its target location Files.copy(fi.openStream(), file.toPath()); // Create the media entity String relativePath = new File(dataDir).toURI().relativize(file.toURI()).getPath(); BuntataMedia media = new BuntataMedia(null, new Date(), new Date()) .setInternalLink(relativePath).setName(name).setDescription(name).setMediaTypeId(1L); mediaDAO.add(media); // Create the node media entity nodeMediaDAO.add(new BuntataNodeMedia().setMediaId(media.getId()).setNodeId(node.getId())); return true; } } catch (Exception e) { e.printStackTrace(); } } else { throw new ResourceException(Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE); } return false; }
From source file:com.northernwall.hadrian.handler.ImageHandler.java
private void updateImage(Request request, String serviceId) throws IOException, FileUploadException { if (!ServletFileUpload.isMultipartContent(request)) { logger.warn("Trying to upload image for {} but content is not multipart", serviceId); return;/* w ww . jav a 2 s . c o m*/ } logger.info("Trying to upload image for {}", serviceId); ServletFileUpload upload = new ServletFileUpload(); // Parse the request FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); if (!item.isFormField()) { String name = item.getName(); name = name.replace(' ', '-').replace('&', '-').replace('<', '-').replace('>', '-') .replace('/', '-').replace('\\', '-').replace('&', '-').replace('@', '-').replace('?', '-') .replace('^', '-').replace('#', '-').replace('%', '-').replace('=', '-').replace('$', '-') .replace('{', '-').replace('}', '-').replace('[', '-').replace(']', '-').replace('|', '-') .replace(';', '-').replace(':', '-').replace('~', '-').replace('`', '-'); dataAccess.uploadImage(serviceId, name, item.getContentType(), item.openStream()); } } }
From source file:com.runwaysdk.web.SecureFileUploadServlet.java
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { ClientRequestIF clientRequest = (ClientRequestIF) req.getAttribute(ClientConstants.CLIENTREQUEST); boolean isMultipart = ServletFileUpload.isMultipartContent(req); if (!isMultipart) { // TODO Change exception type String msg = "The HTTP Request must contain multipart content."; throw new RuntimeException(msg); }//from w w w.jav a 2 s .co m String fileId = req.getParameter("sessionId").toString().trim(); FileItemFactory factory = new ProgressMonitorFileItemFactory(req, fileId); ServletFileUpload upload = new ServletFileUpload(); upload.setFileItemFactory(factory); try { // Parse the request FileItemIterator iter = upload.getItemIterator(req); while (iter.hasNext()) { FileItemStream item = iter.next(); if (!item.isFormField()) { String fullName = item.getName(); int extensionInd = fullName.lastIndexOf("."); String fileName = fullName.substring(0, extensionInd); String extension = fullName.substring(extensionInd + 1); InputStream stream = item.openStream(); BusinessDTO fileDTO = clientRequest.newSecureFile(fileName, extension, stream); // return the vault id to the dhtmlxVault callback req.getSession().setAttribute("FileUpload.Progress." + fileId, fileDTO.getId()); } } } catch (FileUploadException e) { throw new FileWriteExceptionDTO(e.getLocalizedMessage()); } catch (RuntimeException e) { req.getSession().setAttribute("FileUpload.Progress." + fileId, "fail: " + e.getLocalizedMessage()); } }
From source file:cc.vidr.servlet.DatumImportServlet.java
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { try {/*from w w w . ja va 2 s . co m*/ ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iterator = upload.getItemIterator(req); while (iterator.hasNext()) { FileItemStream item = iterator.next(); if (item.isFormField()) continue; String filename = item.getName(); if (filename.isEmpty()) continue; InputStream stream = item.openStream(); resp.getWriter().println("<p>"); try { resp.getWriter().println("Loading '" + filename + "'... "); Program program = new Program(stream); program.parse(); program.assertFacts(Server.factDatabase); program.assertRules(Server.ruleDatabase); resp.getWriter().println("OK"); } catch (RecognitionException e) { resp.getWriter().println("Malformed input: " + e.getMessage()); } catch (UnsafeException e) { resp.getWriter().println("Unsafe rule or non-ground fact encountered: " + e.getMessage()); } catch (IOException e) { resp.getWriter().println("Error opening file: " + e.getMessage()); } resp.getWriter().println("</p>"); } } catch (FileUploadException e) { throw new ServletException(e); } doGet(req, resp); }
From source file:com.cubusmail.gwtui.server.services.AttachmentUploadServlet.java
/** * Create a MimeBodyPart.// w w w .j a v a 2 s. com * * @param item * @return * @throws MessagingException * @throws IOException */ private DataSource createDataSource(FileItemStream item) throws MessagingException, IOException { final String fileName = FilenameUtils.getName(item.getName()); final String contentType = item.getContentType(); final InputStream stream = item.openStream(); ByteArrayDataSource source = new ByteArrayDataSource(stream, contentType); source.setName(fileName); return source; }
From source file:com.fizzbuzz.vroom.extension.googlecloudstorage.api.resource.GcsFilesResource.java
/** * * @param rep//from w w w .j a v a 2 s.co m */ public void postResource(final Representation rep) { if (rep == null) setStatus(Status.CLIENT_ERROR_BAD_REQUEST); else { try { FileUpload fileUpload = new FileUpload(); FileItemIterator fileItemIterator = fileUpload.getItemIterator(new RepresentationContext(rep)); if (fileItemIterator.hasNext()) { FileItemStream fileItemStream = fileItemIterator.next(); validateFileItemStream(fileItemStream); String fileName = fileItemStream.getName(); byte[] bytes = ByteStreams.toByteArray(fileItemStream.openStream()); F file = createFile(fileName); mBiz.create(file, bytes); // we're not going to send a representation of the file back to the client, since they probably // don't want that. Instead, we'll send them a 201, with the URL to the created file in the // Location header of the response. getResponse().setStatus(Status.SUCCESS_CREATED); // set the Location response header String uri = getElementUri(file); getResponse().setLocationRef(uri); mLogger.info("created new file resource at: {}", uri); } } catch (FileUploadException e) { throw new IllegalArgumentException( "caught FileUploadException while attempting to parse " + "multipart form", e); } catch (IOException e) { throw new IllegalArgumentException( "caught IOException while attempting to parse multipart " + "form", e); } } }
From source file:act.util.UploadFileStorageService.java
private ISObject _store(FileItemStream fileItemStream) throws IOException { String filename = fileItemStream.getName(); String key = newKey(filename); File tmpFile = getFile(key);//from w w w . j av a2 s . c om InputStream input = fileItemStream.openStream(); ThresholdingByteArrayOutputStream output = new ThresholdingByteArrayOutputStream(inMemoryCacheThreshold, tmpFile); IO.copy(input, output); ISObject retVal; if (output.exceedThreshold) { retVal = getFull(key); } else { int size = output.written; byte[] buf = output.buf(); retVal = SObject.of(key, buf, size); } if (S.notBlank(filename)) { retVal.setFilename(filename); } String contentType = fileItemStream.getContentType(); if (null != contentType) { retVal.setContentType(contentType); } return retVal; }