List of usage examples for org.apache.commons.fileupload FileItemStream getName
String getName();
From source file:org.opencastproject.workingfilerepository.impl.WorkingFileRepositoryRestEndpoint.java
@POST @Produces(MediaType.TEXT_HTML)/*from w w w . j ava 2 s . co m*/ @Path(WorkingFileRepository.COLLECTION_PATH_PREFIX + "{collectionId}") @RestQuery(name = "putInCollection", description = "Store a file in working repository under ./collectionId/filename", returnDescription = "The URL to access the stored file", pathParameters = { @RestParameter(name = "collectionId", description = "the colection identifier", isRequired = true, type = STRING) }, restParameters = { @RestParameter(name = "file", description = "the filename", isRequired = true, type = FILE) }, reponses = { @RestResponse(responseCode = SC_OK, description = "OK, file stored") }) public Response restPutInCollection(@PathParam("collectionId") String collectionId, @Context HttpServletRequest request) throws Exception { if (ServletFileUpload.isMultipartContent(request)) { for (FileItemIterator iter = new ServletFileUpload().getItemIterator(request); iter.hasNext();) { FileItemStream item = iter.next(); if (item.isFormField()) { continue; } URI url = this.putInCollection(collectionId, item.getName(), item.openStream()); return Response.ok(url.toString()).build(); } } return Response.serverError().status(400).build(); }
From source file:org.opendatakit.aggregate.parser.MultiPartFormData.java
/** * Construct a mult-part form data container by parsing a multi part form * request into a set of multipartformitems. The information are stored in * items and are indexed by either the field name or the file name (or both) * provided in the http submission// www.j ava 2 s. c o m * * @param req * an HTTP request from a multipart form * * @throws FileUploadException * @throws IOException */ public MultiPartFormData(HttpServletRequest req) throws FileUploadException, IOException { simpleFieldNameMap = new HashMap<String, String>(); fieldNameMap = new HashMap<String, MultiPartFormItem>(); fileNameMap = new HashMap<String, MultiPartFormItem>(); fileNameWithoutExtensionNameMap = new HashMap<String, MultiPartFormItem>(); ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); int size = req.getContentLength(); if (size > 0) { upload.setFileSizeMax(size); } else { upload.setFileSizeMax(ParserConsts.FILE_SIZE_MAX); } List<MultiPartFormItem> fileNameList = new ArrayList<MultiPartFormItem>(); FileItemIterator items = upload.getItemIterator(req); while (items.hasNext()) { FileItemStream item = items.next(); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); BufferedInputStream formStream = new BufferedInputStream(item.openStream()); // TODO: determine ways to possibly improve efficiency int nextByte = formStream.read(); while (nextByte != -1) { byteStream.write(nextByte); nextByte = formStream.read(); } formStream.close(); if (item.isFormField()) { simpleFieldNameMap.put(item.getFieldName(), byteStream.toString()); } else { MultiPartFormItem data = new MultiPartFormItem(item.getFieldName(), item.getName(), item.getContentType(), byteStream); String fieldName = item.getFieldName(); if (fieldName != null) { fieldNameMap.put(fieldName, data); } String fileName = item.getName(); if (fileName != null && fileName.length() != 0) { fileNameList.add(data); } } } // Find the common prefix to the filenames being uploaded... // Deal with Windows backslash file separator... boolean first = true; String[] commonPath = null; int commonPrefix = 0; for (MultiPartFormItem e : fileNameList) { String fullFilePath = e.getFilename(); if (first) { commonPath = fullFilePath.split("[/\\\\]"); commonPrefix = commonPath.length - 1; // everything but // filename... first = false; } else { String[] path = fullFilePath.split("[/\\\\]"); int pathPrefix = path.length - 1; // everything but // filename... if (pathPrefix < commonPrefix) commonPrefix = pathPrefix; for (int i = 0; i < commonPrefix; ++i) { if (!commonPath[i].equals(path[i])) { commonPrefix = i; break; } } } } // and now go back through the attachments, adjusting the filename // and building the filename mapping. for (MultiPartFormItem e : fileNameList) { String fullFilePath = e.getFilename(); String[] filePath = fullFilePath.split("[/\\\\]"); StringBuilder b = new StringBuilder(); first = true; // start at the first entry after the common prefix... for (int i = commonPrefix; i < filePath.length; ++i) { if (!first) { b.append("/"); } first = false; b.append(filePath[i]); } // and construct the filename with common directory prefix // stripped. String fileName = b.toString(); e.setFilename(fileName); if (fileName != null) { // TODO: possible bug in ODK collect truncating file extension // may need to remove this code after ODK collect is fixed int indexOfExtension = fileName.lastIndexOf("."); if (indexOfExtension > 0) { fileNameWithoutExtensionNameMap.put(fileName.substring(0, indexOfExtension), e); } fileNameMap.put(fileName, e); } } }
From source file:org.openehealth.ipf.platform.camel.lbs.http.process.HttpResourceHandler.java
private void extractFromSinglePart(String subUnit, ResourceList resources, FileItemIterator iter) throws Exception { FileItemStream next = iter.next(); InputStream inputStream = next.openStream(); try {/*from w ww . jav a2 s . co m*/ handleResource(subUnit, resources, next.getContentType(), next.getName(), next.getFieldName(), inputStream); } finally { inputStream.close(); } }
From source file:org.operamasks.faces.render.widget.AjaxFileUploadRenderer.java
private boolean isFieldNull(FileItemStream item) { return "".equals(item.getName()); }
From source file:org.polymap.rap.updownload.upload.FileUploadServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try {//from ww w. ja v a 2s .c om FileItemIterator it = fileUpload.getItemIterator(req); while (it.hasNext()) { FileItemStream item = it.next(); String name = item.getFieldName(); InputStream in = item.openStream(); try { if (item.isFormField()) { log.info("Form field " + name + " with value " + Streams.asString(in) + " detected."); } else { log.info("File field " + name + " with file name " + item.getName() + " detected."); String key = req.getParameter("handler"); assert key != null; IUploadHandler handler = handlers.get(key); // for the upload field we always get just one item (which has the length of the request!?) int length = req.getContentLength(); handler.uploadStarted(item.getName(), item.getContentType(), length, in); } } finally { IOUtils.closeQuietly(in); } } } catch (Exception e) { log.warn("", e); throw new RuntimeException(e); } }
From source file:org.polymap.rap.updownload.upload.UploadService.java
@Override public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { try {/*from w w w . java2s. c om*/ FileItemIterator it = fileUpload.getItemIterator(request); while (it.hasNext()) { FileItemStream item = it.next(); try (InputStream in = item.openStream()) { if (item.isFormField()) { log.info("Form field " + item.getFieldName() + " with value " + Streams.asString(in) + " detected."); } else { log.info("File field " + item.getFieldName() + " with file name " + item.getName() + " detected."); String handlerId = request.getParameter(ID_REQUEST_PARAM); assert handlerId != null; IUploadHandler handler = handlers.get(handlerId); ClientFile clientFile = new ClientFile() { @Override public String getName() { return item.getName(); } @Override public String getType() { return item.getContentType(); } @Override public long getSize() { // for the upload field we always get just one item (which has the length of the request!?) return request.getContentLength(); } }; handler.uploadStarted(clientFile, in); } } } } catch (Exception e) { log.warn("", e); throw new RuntimeException(e); } }
From source file:org.rapidcontext.app.web.AppWebService.java
/** * Processes a file upload request. This is used when files are * POST:ed to the special upload URL./*from w w w .j a v a 2 s . c o m*/ * * @param request the request to process */ protected void processUpload(Request request) { Session session = (Session) Session.activeSession.get(); if (session == null) { errorUnauthorized(request); return; } try { FileItemStream stream = request.getNextFile(); if (stream == null) { errorBadRequest(request, "Missing file data"); return; } String fileName = stream.getName(); if (fileName.lastIndexOf("/") >= 0) { fileName = fileName.substring(fileName.lastIndexOf("/") + 1); } if (fileName.lastIndexOf("\\") >= 0) { fileName = fileName.substring(fileName.lastIndexOf("\\") + 1); } String fileId = request.getPath(); while (fileId != null && fileId.startsWith("/")) { fileId = fileId.substring(1); } if (fileId == null || fileId.trim().length() == 0) { fileId = fileName; } session.removeFile(fileId); File file = FileUtil.tempFile(fileName); FileUtil.copy(stream.openStream(), file); session.addFile(fileId, file); request.sendText(Mime.TEXT[0], "Session file " + fileId + " uploaded"); } catch (IOException e) { LOG.log(Level.WARNING, "failed to process file upload", e); errorBadRequest(request, e.getMessage()); } }
From source file:org.restlet.example.ext.fileupload.FileUploadServerResource.java
@Post public Representation accept(Representation entity) throws Exception { Representation result = null;//from w w w.j a v a 2 s . com if (entity != null && MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) { // 1/ Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1000240); // 2/ Create a new file upload handler based on the Restlet // FileUpload extension that will parse Restlet requests and // generates FileItems. RestletFileUpload upload = new RestletFileUpload(factory); // 3/ Request is parsed by the handler which generates a // list of FileItems FileItemIterator fileIterator = upload.getItemIterator(entity); // Process only the uploaded item called "fileToUpload" // and return back boolean found = false; while (fileIterator.hasNext() && !found) { FileItemStream fi = fileIterator.next(); if (fi.getFieldName().equals("fileToUpload")) { // For the matter of sample code, it filters the multo // part form according to the field name. found = true; // consume the stream immediately, otherwise the stream // will be closed. StringBuilder sb = new StringBuilder("media type: "); sb.append(fi.getContentType()).append("\n"); sb.append("file name : "); sb.append(fi.getName()).append("\n"); BufferedReader br = new BufferedReader(new InputStreamReader(fi.openStream())); String line = null; while ((line = br.readLine()) != null) { sb.append(line); } sb.append("\n"); result = new StringRepresentation(sb.toString(), MediaType.TEXT_PLAIN); } } } else { // POST request with no entity. setStatus(Status.CLIENT_ERROR_BAD_REQUEST); } return result; }
From source file:org.retrostore.request.RequestDataImpl.java
/** * Parses a multipart request and gets its files and parameters. *///from ww w . j av a 2 s. c o m private static void parseMultipartContent(HttpServletRequest request, Map<String, String> formParams, List<UploadFile> uploadFiles) { if (!ServletFileUpload.isMultipartContent(request)) { return; } ServletFileUpload upload = new ServletFileUpload(); try { FileItemIterator itemIterator = upload.getItemIterator(request); while (itemIterator.hasNext()) { FileItemStream file = itemIterator.next(); ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); ByteStreams.copy(file.openStream(), bytesOut); byte[] bytes = bytesOut.toByteArray(); // If an item has a name, we think it's a file, otherwise we treat it as a regular string // parameter. if (!Strings.isNullOrEmpty(file.getName())) { uploadFiles.add(new UploadFile(file.getFieldName(), file.getName(), bytes)); } else { String str = new String(bytes, StandardCharsets.UTF_8); formParams.put(file.getFieldName(), str); } } } catch (FileUploadException | IOException e) { LOG.log(Level.WARNING, "Cannot parse request for filename.", e); } }
From source file:org.sosy_lab.cpachecker.appengine.server.resource.TasksServerResource.java
@Override public Representation createTaskFromHtml(Representation input) throws IOException { List<String> errors = new LinkedList<>(); Map<String, Object> settings = new HashMap<>(); Map<String, String> options = new HashMap<>(); ServletFileUpload upload = new ServletFileUpload(); try {/*from www.j ava 2 s.c o m*/ FileItemIterator iter = upload.getItemIterator(ServletUtils.getRequest(getRequest())); while (iter.hasNext()) { FileItemStream item = iter.next(); InputStream stream = item.openStream(); if (item.isFormField()) { String value = Streams.asString(stream); switch (item.getFieldName()) { case "specification": value = (value.equals("")) ? null : value; settings.put("specification", value); break; case "configuration": value = (value.equals("")) ? null : value; settings.put("configuration", value); break; case "disableOutput": options.put("output.disable", "true"); break; case "disableExportStatistics": options.put("statistics.export", "false"); break; case "dumpConfig": options.put("configuration.dumpFile", "UsedConfiguration.properties"); break; case "logLevel": options.put("log.level", value); break; case "machineModel": options.put("analysis.machineModel", value); break; case "wallTime": options.put("limits.time.wall", value); break; case "instanceType": options.put("gae.instanceType", value); break; case "programText": if (!value.isEmpty()) { settings.put("programName", "program.c"); settings.put("programText", value); } break; } } else { if (settings.get("programText") == null) { settings.put("programName", item.getName()); settings.put("programText", IOUtils.toString(stream)); } } } } catch (FileUploadException | IOException e) { getLogger().log(Level.WARNING, "Could not upload program file.", e); errors.add("task.program.CouldNotUpload"); } settings.put("options", options); Task task = null; if (errors.isEmpty()) { TaskBuilder taskBuilder = new TaskBuilder(); task = taskBuilder.fromMap(settings); errors = taskBuilder.getErrors(); } if (errors.isEmpty()) { try { Configuration config = Configuration.builder().setOptions(task.getOptions()).build(); new GAETaskQueueTaskExecutor(config).execute(task); } catch (InvalidConfigurationException e) { errors.add("error.invalidConfiguration"); } } if (errors.isEmpty()) { getResponse().setStatus(Status.SUCCESS_CREATED); redirectSeeOther("/tasks/" + task.getKey()); return getResponseEntity(); } getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST); return FreemarkerUtil.templateBuilder().context(getContext()).addData("task", task) .addData("errors", errors).addData("allowedOptions", DefaultOptions.getDefaultOptions()) .addData("defaultOptions", DefaultOptions.getImmutableOptions()) .addData("specifications", DefaultOptions.getSpecifications()) .addData("configurations", DefaultOptions.getConfigurations()) .addData("cpacheckerVersion", CPAchecker.getCPAcheckerVersion()).templateName("root.ftl").build(); }