List of usage examples for org.apache.commons.fileupload FileItemStream isFormField
boolean isFormField();
FileItem
instance represents a simple form field. From source file:org.celstec.arlearn2.upload.UploadGameServlet.java
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { long gameId = 0l; String auth = null;/*from w w w . j ava 2 s. com*/ try { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(req); String json = ""; while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { String value = Streams.asString(stream); if ("gameId".equals(name)) gameId = Long.parseLong(value); if ("auth".equals(name)) auth = value; } else { json = Streams.asString(stream); } } res.setContentType("text/plain"); JSONObject jObject = new JSONObject(json); Object deserialized = JsonBeanDeserializer.deserialize(json); if (deserialized instanceof GamePackage && ((GamePackage) deserialized).getGame() != null) unpackGame((GamePackage) deserialized, req, auth); if (deserialized instanceof RunPackage && ((RunPackage) deserialized).getRun() != null) unpackRun((RunPackage) deserialized, req, gameId, auth); } catch (Exception ex) { throw new ServletException(ex); } }
From source file:org.codelabor.system.file.web.servlet.FileUploadStreamServlet.java
@Override protected void upload(HttpServletRequest request, HttpServletResponse response) throws Exception { WebApplicationContext ctx = WebApplicationContextUtils .getRequiredWebApplicationContext(this.getServletContext()); FileManager fileManager = (FileManager) ctx.getBean("fileManager"); boolean isMultipart = ServletFileUpload.isMultipartContent(request); Map<String, Object> paramMap = RequestUtils.getParameterMap(request); if (logger.isDebugEnabled()) { logger.debug(paramMap.toString()); }/*from w w w .j av a 2s . c o m*/ String mapId = (String) paramMap.get("mapId"); RepositoryType acceptedRepositoryType = repositoryType; String requestedRepositoryType = (String) paramMap.get("repositoryType"); if (StringUtils.isNotEmpty(requestedRepositoryType)) { acceptedRepositoryType = RepositoryType.valueOf(requestedRepositoryType); } if (isMultipart) { ServletFileUpload upload = new ServletFileUpload(); upload.setFileSizeMax(fileSizeMax); upload.setSizeMax(requestSizeMax); upload.setHeaderEncoding(characterEncoding); upload.setProgressListener(new FileUploadProgressListener()); try { FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream fileItemSteam = iter.next(); if (logger.isDebugEnabled()) { logger.debug(fileItemSteam.toString()); } FileDTO fileDTO = null; if (fileItemSteam.isFormField()) { paramMap.put(fileItemSteam.getFieldName(), Streams.asString(fileItemSteam.openStream(), characterEncoding)); } else { if (fileItemSteam.getName() == null || fileItemSteam.getName().length() == 0) continue; // set DTO fileDTO = new FileDTO(); fileDTO.setMapId(mapId); fileDTO.setRealFilename(FilenameUtils.getName(fileItemSteam.getName())); if (acceptedRepositoryType == RepositoryType.FILE_SYSTEM) { fileDTO.setUniqueFilename(getUniqueFilename()); } fileDTO.setContentType(fileItemSteam.getContentType()); fileDTO.setRepositoryPath(realRepositoryPath); if (logger.isDebugEnabled()) { logger.debug(fileDTO.toString()); } UploadUtils.processFile(acceptedRepositoryType, fileItemSteam.openStream(), fileDTO); } if (fileDTO != null) fileManager.insertFile(fileDTO); } } catch (FileUploadException e) { e.printStackTrace(); logger.error(e.getMessage()); } catch (Exception e) { e.printStackTrace(); logger.error(e.getMessage()); } } else { paramMap = RequestUtils.getParameterMap(request); } try { processParameters(paramMap); } catch (Exception e) { e.printStackTrace(); logger.error(e.getMessage()); } dispatch(request, response, forwardPathUpload); }
From source file:org.collectionspace.chain.controller.WebUIRequest.java
private void initRequest(UIUmbrella umbrella, HttpServletRequest request, HttpServletResponse response, List<String> p) throws IOException, UIException { this.request = request; this.response = response; boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(); // Parse the request FileItemIterator iter;/* w ww .j av a2 s.c om*/ try { 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."); // Process the input stream contentHeaders = item.getHeaders(); uploadName = item.getName(); ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); if (item != null) { InputStream stream = item.openStream(); IOUtils.copy(stream, byteOut); new TeeInputStream(stream, byteOut); } bytebody = byteOut.toByteArray(); } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { body = IOUtils.toString(request.getInputStream(), "UTF-8"); } this.ppath = p.toArray(new String[0]); if (!(umbrella instanceof WebUIUmbrella)) throw new UIException("Bad umbrella"); this.umbrella = (WebUIUmbrella) umbrella; session = calculateSessionId(); }
From source file:org.cvit.cabig.dmr.cmef.server.SubmitJobResource.java
@Post("multi") public Representation submitJob(Representation formRep) { RestletFileUpload upload = new RestletFileUpload(); ComputationJob job = new ComputationJob(); boolean inIframe = false; try {//from w ww. j a v a 2 s . c om FileItemIterator items = upload.getItemIterator(formRep); List<ParameterValue> values = new ArrayList<ParameterValue>(); job.setParameterValues(values); State state = State.TITLE; while (items.hasNext()) { FileItemStream item = items.next(); InputStream itemStream = item.openStream(); switch (state) { case TITLE: job.setTitle(Streams.asString(itemStream)); state = State.DESC; break; case DESC: job.setDescription(Streams.asString(itemStream)); state = State.COMMENTS; break; case COMMENTS: job.setComment(Streams.asString(itemStream)); state = State.PARAMS; break; case PARAMS: if (item.getFieldName().equals("iframe")) { inIframe = Boolean.parseBoolean(Streams.asString(itemStream)); } else { Parameter param = new Parameter(); param.setName(parseParamName(item.getFieldName())); ParameterValue value = new ParameterValue(); if (item.isFormField()) { value.setValue(Streams.asString(itemStream)); } else { value.setValue(storeFile(item.getName(), itemStream).getSource()); } value.setJob(job); value.setParameter(param); param.setValue(value); values.add(value); } break; } } } catch (Exception e) { throw new ResourceException(Status.SERVER_ERROR_INTERNAL, "Exception processing submit job form: " + e.getMessage(), e); } job = addNewJob(job); ComputationJob startedJob = startJob(job); if (inIframe) { return new StringRepresentation(buildIframeResponse(job), MediaType.TEXT_HTML); } else { Reference jobRef = getNamespace().jobRef(entryName, modelName, getResolver().getJobName(startedJob.getId()), true); redirectSeeOther(jobRef); return new StringRepresentation("Job submitted, URL: " + jobRef.toString() + "."); } }
From source file:org.daxplore.presenter.server.servlets.AdminUploadServlet.java
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) { try {//w ww .ja v a 2 s .co m long time = System.nanoTime(); int statusCode = HttpServletResponse.SC_OK; response.setContentType("text/html; charset=UTF-8"); ServletFileUpload upload = new ServletFileUpload(); PersistenceManager pm = null; String prefix = null; try { FileItemIterator fileIterator = upload.getItemIterator(request); String fileName = ""; byte[] fileData = null; while (fileIterator.hasNext()) { FileItemStream item = fileIterator.next(); try (InputStream stream = item.openStream()) { if (item.isFormField()) { if (item.getFieldName().equals("prefix")) { prefix = Streams.asString(stream); } else { throw new BadRequestException("Form contains extra fields"); } } else { fileName = item.getName(); fileData = IOUtils.toByteArray(stream); } } } if (SharedResourceTools.isSyntacticallyValidPrefix(prefix)) { if (fileData != null && !fileName.equals("")) { pm = PMF.get().getPersistenceManager(); unzipAll(pm, prefix, fileData); } else { throw new BadRequestException("No file uploaded"); } } else { throw new BadRequestException("Request made with invalid prefix: '" + prefix + "'"); } logger.log(Level.INFO, "Unpacked new data for prefix '" + prefix + "' in " + ((System.nanoTime() - time) / 1000000000.0) + " seconds"); } catch (FileUploadException | IOException | BadRequestException e) { logger.log(Level.WARNING, e.getMessage(), e); statusCode = HttpServletResponse.SC_BAD_REQUEST; } catch (InternalServerException e) { logger.log(Level.SEVERE, e.getMessage(), e); statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; } catch (DeadlineExceededException e) { logger.log(Level.SEVERE, "Timeout when uploading new data for prefix '" + prefix + "'", e); // the server is currently unavailable because it is overloaded (hopefully) statusCode = HttpServletResponse.SC_SERVICE_UNAVAILABLE; } finally { if (pm != null) { pm.close(); } } response.setStatus(statusCode); try (PrintWriter resWriter = response.getWriter()) { if (resWriter != null) { resWriter.write(Integer.toString(statusCode)); resWriter.close(); } } } catch (IOException | RuntimeException e) { logger.log(Level.SEVERE, "Unexpected exception: " + e.getMessage(), e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
From source file:org.duracloud.common.rest.RestUtilImpl.java
/** * Retrieves the contents of the HTTP Request. * * @return InputStream from the request/* www.ja v a 2s . c om*/ */ @Override public RequestContent getRequestContent(HttpServletRequest request, HttpHeaders headers) throws Exception { RequestContent rContent = null; // See if the request is a multi-part file upload request if (ServletFileUpload.isMultipartContent(request)) { // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(); // Parse the request, use the first available File item FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); if (!item.isFormField()) { rContent = new RequestContent(); rContent.contentStream = item.openStream(); rContent.mimeType = item.getContentType(); FileItemHeaders itemHeaders = item.getHeaders(); if (itemHeaders != null) { String contentLength = itemHeaders.getHeader("Content-Length"); if (contentLength != null) { rContent.size = Long.parseLong(contentLength); } } break; } } } else { // If the content stream was not found as a multipart, // try to use the stream from the request directly rContent = new RequestContent(); rContent.contentStream = request.getInputStream(); if (request.getContentLength() >= 0) { rContent.size = request.getContentLength(); } } // Attempt to set the mime type and size if not already set if (rContent != null) { if (rContent.mimeType == null) { MediaType mediaType = headers.getMediaType(); if (mediaType != null) { rContent.mimeType = mediaType.toString(); } } if (rContent.size == 0) { List<String> lengthHeaders = headers.getRequestHeader("Content-Length"); if (lengthHeaders != null && lengthHeaders.size() > 0) { rContent.size = Long.parseLong(lengthHeaders.get(0)); } } } return rContent; }
From source file:org.duracloud.duradmin.spaces.controller.ContentItemUploadController.java
@RequestMapping(value = "/spaces/content/upload", method = RequestMethod.POST) public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { try {/*from w w w .java2 s. c om*/ log.debug("handling request..."); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(request); String spaceId = null; String storeId = null; String contentId = null; List<ContentItem> results = new ArrayList<ContentItem>(); while (iter.hasNext()) { FileItemStream item = iter.next(); if (item.isFormField()) { String value = Streams.asString(item.openStream(), "UTF-8"); if (item.getFieldName().equals("spaceId")) { log.debug("setting spaceId: {}", value); spaceId = value; } else if (item.getFieldName().equals("storeId")) { storeId = value; } else if (item.getFieldName().equals("contentId")) { contentId = value; } } else { log.debug("setting fileStream: {}", item); if (StringUtils.isBlank(spaceId)) { throw new IllegalArgumentException("space id required."); } ContentItem ci = new ContentItem(); if (StringUtils.isBlank(contentId)) { contentId = item.getName(); } ci.setContentId(contentId); ci.setSpaceId(spaceId); ci.setStoreId(storeId); ci.setContentMimetype(item.getContentType()); ContentStore contentStore = contentStoreManager.getContentStore(ci.getStoreId()); ContentItemUploadTask task = new ContentItemUploadTask(ci, contentStore, item.openStream(), request.getUserPrincipal().getName()); task.execute(); ContentItem result = new ContentItem(); Authentication auth = (Authentication) SecurityContextHolder.getContext().getAuthentication(); SpaceUtil.populateContentItem(ContentItemController.getBaseURL(request), result, ci.getSpaceId(), ci.getContentId(), contentStore, auth); results.add(result); contentId = null; } } return new ModelAndView("javascriptJsonView", "results", results); } catch (Exception ex) { ex.printStackTrace(); throw ex; } }
From source file:org.eclipse.rap.addons.fileupload.internal.FileUploadProcessor.java
void handleFileUpload(HttpServletRequest request, HttpServletResponse response) throws IOException { try {/* w ww.j a v a 2 s.co m*/ ServletFileUpload upload = createUpload(); FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); if (!item.isFormField()) { receive(item); } } if (tracker.isEmpty()) { String errorMessage = "No file upload data found in request"; tracker.setException(new Exception(errorMessage)); tracker.handleFailed(); response.sendError(HttpServletResponse.SC_BAD_REQUEST, errorMessage); } else { tracker.handleFinished(); } } catch (Exception exception) { Throwable cause = exception.getCause(); if (cause instanceof FileSizeLimitExceededException) { exception = (Exception) cause; } tracker.setException(exception); tracker.handleFailed(); int errorCode = exception instanceof FileSizeLimitExceededException ? HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE : HttpServletResponse.SC_INTERNAL_SERVER_ERROR; response.sendError(errorCode, exception.getMessage()); } }
From source file:org.eclipse.scout.rt.ui.html.json.UploadRequestHandler.java
protected void readUploadData(HttpServletRequest httpReq, long maxSize, Map<String, String> uploadProperties, List<BinaryResource> uploadResources) throws FileUploadException, IOException { ServletFileUpload upload = new ServletFileUpload(); upload.setHeaderEncoding(StandardCharsets.UTF_8.name()); upload.setSizeMax(maxSize);//w ww. ja v a2 s.c om for (FileItemIterator it = upload.getItemIterator(httpReq); it.hasNext();) { FileItemStream item = it.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { // Handle non-file fields (interpreted as properties) uploadProperties.put(name, Streams.asString(stream, StandardCharsets.UTF_8.name())); } else { // Handle files String filename = item.getName(); if (StringUtility.hasText(filename)) { String[] parts = StringUtility.split(filename, "[/\\\\]"); filename = parts[parts.length - 1]; } String contentType = item.getContentType(); byte[] content = IOUtility.getContent(stream); // Info: we cannot set the charset property for uploaded files here, because we simply don't know it. // the only thing we could do is to guess the charset (encoding) by reading the byte contents of // uploaded text files (for binary file types the encoding is not relevant). However: currently we // do not set the charset at all. uploadResources.add(new BinaryResource(filename, contentType, content)); } } }
From source file:org.ejbca.ui.web.HttpUpload.java
/** * Creates a new upload state and receives all file and parameter data. * This constructor can only be called once per request. * //w ww .j a va2 s .co m * Use getParameterMap() and getFileMap() on the new object to access the data. * * @param request The servlet request object. * @param fileFields The names of the file fields to receive uploaded data from. * @param maxbytes Maximum file size. * @throws IOException if there are network problems, etc. * @throws FileUploadException if the request is invalid. */ @SuppressWarnings("unchecked") // Needed in some environments, and detected as unnecessary in others. Do not remove! public HttpUpload(HttpServletRequest request, String[] fileFields, int maxbytes) throws IOException, FileUploadException { if (ServletFileUpload.isMultipartContent(request)) { final Map<String, ArrayList<String>> paramTemp = new HashMap<String, ArrayList<String>>(); fileMap = new HashMap<String, byte[]>(); final ServletFileUpload upload = new ServletFileUpload(); final FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { final FileItemStream item = iter.next(); final String name = item.getFieldName(); if (item.isFormField()) { ArrayList<String> values = paramTemp.get(name); if (values == null) { values = new ArrayList<String>(); paramTemp.put(name, values); } values.add(Streams.asString(item.openStream(), request.getCharacterEncoding())); } else if (ArrayUtils.contains(fileFields, name)) { byte[] data = getFileBytes(item, maxbytes); if (data != null && data.length > 0) { fileMap.put(name, data); } } } // Convert to String,String[] map parameterMap = new ParameterMap(); for (Entry<String, ArrayList<String>> entry : paramTemp.entrySet()) { final ArrayList<String> values = entry.getValue(); final String[] valuesArray = new String[values.size()]; parameterMap.put(entry.getKey(), values.toArray(valuesArray)); } } else { parameterMap = new ParameterMap(request.getParameterMap()); fileMap = new HashMap<String, byte[]>(); } }