List of usage examples for org.apache.commons.fileupload FileItemStream getName
String getName();
From source file:com.webpagebytes.cms.controllers.FileController.java
public void uploadFolder(HttpServletRequest request, HttpServletResponse response, String requestUri) throws WPBException { try {//from ww w .j a va2s . c om ServletFileUpload upload = new ServletFileUpload(); upload.setHeaderEncoding("UTF-8"); FileItemIterator iterator = upload.getItemIterator(request); WPBFile ownerFile = null; Map<String, WPBFile> subfolderFiles = new HashMap<String, WPBFile>(); while (iterator.hasNext()) { FileItemStream item = iterator.next(); if (item.isFormField() && item.getFieldName().equals("ownerExtKey")) { String ownerExtKey = Streams.asString(item.openStream()); ownerFile = getDirectory(ownerExtKey, adminStorage); } else if (!item.isFormField() && item.getFieldName().equals("file")) { String fullName = item.getName(); String directoryPath = getDirectoryFromLongName(fullName); String fileName = getFileNameFromLongName(fullName); Map<String, WPBFile> tempSubFolders = checkAndCreateSubDirectory(directoryPath, ownerFile); subfolderFiles.putAll(tempSubFolders); // delete the existing file WPBFile existingFile = getFileFromDirectory(subfolderFiles.get(directoryPath), fileName); if (existingFile != null) { deleteFile(existingFile, 0); } // create the file WPBFile file = new WPBFile(); file.setExternalKey(adminStorage.getUniqueId()); file.setFileName(fileName); file.setLastModified(Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTime()); file.setDirectoryFlag(0); addFileToDirectory(subfolderFiles.get(directoryPath), file, item.openStream()); } } org.json.JSONObject returnJson = new org.json.JSONObject(); returnJson.put(DATA, jsonObjectConverter.JSONFromObject(null)); httpServletToolbox.writeBodyResponseAsJson(response, returnJson, null); } catch (Exception e) { Map<String, String> errors = new HashMap<String, String>(); errors.put("", WPBErrors.WB_CANT_UPDATE_RECORD); httpServletToolbox.writeBodyResponseAsJson(response, jsonObjectConverter.JSONObjectFromMap(null), errors); } }
From source file:fi.helsinki.lib.simplerest.BundleResource.java
@Post public Representation addBitstream(InputRepresentation rep) { Context c = null;/* w w w . j a va2s . com*/ Bundle bundle = null; Bitstream bitstream = null; try { c = getAuthenticatedContext(); bundle = Bundle.find(c, this.bundleId); if (bundle == null) { return errorNotFound(c, "Could not find the bundle."); } Item[] items = bundle.getItems(); RestletFileUpload rfu = new RestletFileUpload(new DiskFileItemFactory()); FileItemIterator iter = rfu.getItemIterator(rep); String description = null; while (iter.hasNext()) { FileItemStream fileItemStream = iter.next(); if (fileItemStream.isFormField()) { String key = fileItemStream.getFieldName(); String value = IOUtils.toString(fileItemStream.openStream(), "UTF-8"); if (key.equals("description")) { description = value; } else { return error(c, "Unexpected attribute: " + key, Status.CLIENT_ERROR_BAD_REQUEST); } } else { if (bitstream != null) { return error(c, "Only one file can added in one request.", Status.CLIENT_ERROR_BAD_REQUEST); } String name = fileItemStream.getName(); bitstream = bundle.createBitstream(fileItemStream.openStream()); bitstream.setName(name); bitstream.setSource(name); BitstreamFormat bf = FormatIdentifier.guessFormat(c, bitstream); bitstream.setFormat(bf); } } if (bitstream == null) { return error(c, "Request does not contain file(?)", Status.CLIENT_ERROR_BAD_REQUEST); } if (description != null) { bitstream.setDescription(description); } bitstream.update(); items[0].update(); // This updates at least the // sequence ID of the bitstream. c.complete(); } catch (AuthorizeException ae) { return error(c, "Unauthorized", Status.CLIENT_ERROR_UNAUTHORIZED); } catch (Exception e) { return errorInternal(c, e.toString()); } return successCreated("Bitstream created.", baseUrl() + BitstreamResource.relativeUrl(bitstream.getID())); }
From source file:com.vmware.photon.controller.api.frontend.resources.image.ImagesResource.java
private Task parseImageDataFromRequest(HttpServletRequest request) throws InternalException, ExternalException { Task task = null;/* w w w . j av a 2 s . co m*/ ServletFileUpload fileUpload = new ServletFileUpload(); FileItemIterator iterator = null; InputStream itemStream = null; try { ImageReplicationType replicationType = null; iterator = fileUpload.getItemIterator(request); while (iterator.hasNext()) { FileItemStream item = iterator.next(); itemStream = item.openStream(); if (item.isFormField()) { String fieldName = item.getFieldName(); switch (fieldName.toUpperCase()) { case "IMAGEREPLICATION": replicationType = ImageReplicationType.valueOf(Streams.asString(itemStream).toUpperCase()); break; default: logger.warn(String.format("The parameter '%s' is unknown in image upload.", fieldName)); } } else { if (replicationType == null) { throw new ImageUploadException( "ImageReplicationType is required and should be encoded before image data in the upload request."); } task = imageFeClient.create(itemStream, item.getName(), replicationType); } itemStream.close(); itemStream = null; } } catch (IllegalArgumentException ex) { throw new ImageUploadException("Image upload receives invalid parameter", ex); } catch (IOException ex) { throw new ImageUploadException("Image upload IOException", ex); } catch (FileUploadException ex) { throw new ImageUploadException("Image upload FileUploadException", ex); } finally { flushRequest(iterator, itemStream); } if (task == null) { throw new ImageUploadException("There is no image stream data in the image upload request."); } return task; }
From source file:controllers.UploadController.java
/** * /*from w ww. j a v a2 s . c o m*/ * This upload method expects a file and simply displays the file in the * multipart upload again to the user (in the correct mime encoding). * * @param context * @return * @throws Exception */ public Result uploadFinish(Context context) throws Exception { // we are using a renderable inner class to stream the input again to // the user Renderable renderable = new Renderable() { @Override public void render(Context context, Result result) { try { // make sure the context really is a multipart context... if (context.isMultipart()) { // This is the iterator we can use to iterate over the // contents // of the request. FileItemIterator fileItemIterator = context.getFileItemIterator(); while (fileItemIterator.hasNext()) { FileItemStream item = fileItemIterator.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); String contentType = item.getContentType(); if (contentType != null) { result.contentType(contentType); } else { contentType = mimeTypes.getMimeType(name); } ResponseStreams responseStreams = context.finalizeHeaders(result); 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 ByteStreams.copy(stream, responseStreams.getOutputStream()); } } } } catch (IOException | FileUploadException exception) { throw new InternalServerErrorException(exception); } } }; return new Result(200).render(renderable); }
From source file:kg12.Ex12_1.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w .ja v a 2s . c om * * @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.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet Ex12_1</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>???</h1>"); // multipart/form-data ?? if (ServletFileUpload.isMultipartContent(request)) { out.println("???<br>"); } else { out.println("?????<br>"); out.close(); return; } // ServletFileUpload?? DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload sfu = new ServletFileUpload(factory); // ??? int fileSizeMax = 1024000; factory.setSizeThreshold(1024); sfu.setSizeMax(fileSizeMax); sfu.setHeaderEncoding("UTF-8"); // ? String format = "%s:%s<br>%n"; // ??????? FileItemIterator fileIt = sfu.getItemIterator(request); while (fileIt.hasNext()) { FileItemStream item = fileIt.next(); if (item.isFormField()) { // out.print("<br>??<br>"); out.printf(format, "??", item.getFieldName()); InputStream is = item.openStream(); // ? byte ?? byte[] b = new byte[255]; // byte? b ???? is.read(b, 0, b.length); // byte? b ? "UTF-8" ??String??? result ? String result = new String(b, "UTF-8"); out.printf(format, "", result); } else { // out.print("<br>??<br>"); out.printf(format, "??", item.getName()); } } out.println("</body>"); out.println("</html>"); } catch (FileUploadException e) { out.println(e + "<br>"); throw new ServletException(e); } catch (Exception e) { out.println(e + "<br>"); throw new ServletException(e); } finally { out.close(); } }
From source file:com.boundlessgeo.geoserver.api.controllers.ImportController.java
/** * API endpoint to import a file or list of files as a new layer or layers into into an existing * store inGeoServer. /* w w w .j a v a 2 s. com*/ * Files are provided as MediaType.MULTIPART_FORM_DATA_VALUE in the request * @param wsName The workspace to import the files into * @param storeName The store to import the layers into. If null, tries to import into a new * store. * @param request The HTTP request * @return a JSON object describing the result of the import. See {@link #get(String, Long) get}. * @throws Exception if the request is invalid, or the file upload fails. */ @RequestMapping(value = "/{wsName:.+}/{storeName:.+}", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public @ResponseBody JSONObj importFile(@PathVariable String wsName, @PathVariable String storeName, HttpServletRequest request) throws Exception { // grab the workspace Catalog catalog = geoServer.getCatalog(); WorkspaceInfo ws = findWorkspace(wsName, catalog); // get the uploaded files FileItemIterator files = doFileUpload(request); if (!files.hasNext()) { throw new BadRequestException("Request must contain one or more files"); } // create a new temp directory for the uploaded file File uploadDir = Files.createTempDirectory("importFile").toFile(); if (!uploadDir.exists()) { throw new RuntimeException("Unable to create directory for file upload"); } uploadDir.deleteOnExit(); // pass off the uploaded file(s) to the importer Directory dir = new Directory(uploadDir); while (files.hasNext()) { FileItemStream item = files.next(); try (InputStream stream = item.openStream()) { String name = item.getName(); dir.accept(name, stream); } } Long id; if (storeName == null) { id = importer.createContextAsync(dir, ws, null); } else { StoreInfo store = findStore(wsName, storeName, geoServer.getCatalog()); id = importer.createContextAsync(dir, ws, store); } return get(wsName, createImport(importer.getTask(id)), request); }
From source file:com.google.sampling.experiential.server.EventServlet.java
private void processCsvUpload(HttpServletRequest req, HttpServletResponse resp) { PrintWriter out = null;/*from w w w. j a va 2 s .c om*/ try { out = resp.getWriter(); } catch (IOException e1) { log.log(Level.SEVERE, "Cannot get an output PrintWriter!"); } try { boolean isDevInstance = isDevInstance(req); ServletFileUpload fileUploadTool = new ServletFileUpload(); fileUploadTool.setSizeMax(50000); resp.setContentType("text/html;charset=UTF-8"); FileItemIterator iterator = fileUploadTool.getItemIterator(req); while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream in = null; try { in = item.openStream(); if (item.isFormField()) { out.println("Got a form field: " + item.getFieldName()); } else { String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); out.println("--------------"); out.println("fileName = " + fileName); out.println("field name = " + fieldName); out.println("contentType = " + contentType); String fileContents = null; fileContents = IOUtils.toString(in); out.println("length: " + fileContents.length()); out.println(fileContents); saveCSV(fileContents, isDevInstance); } } catch (ParseException e) { log.info("Parse Exception: " + e.getMessage()); out.println("Could not parse your csv upload: " + e.getMessage()); } finally { in.close(); } } } catch (SizeLimitExceededException e) { log.info("SizeLimitExceededException: " + e.getMessage()); out.println("You exceeded the maximum size (" + e.getPermittedSize() + ") of the file (" + e.getActualSize() + ")"); return; } catch (IOException e) { log.severe("IOException: " + e.getMessage()); out.println("Error in receiving file."); } catch (FileUploadException e) { log.severe("FileUploadException: " + e.getMessage()); out.println("Error in receiving file."); } }
From source file:com.sonicle.webtop.core.app.AbstractEnvironmentService.java
public void processUpload(HttpServletRequest request, HttpServletResponse response, PrintWriter out) { ServletFileUpload upload = null;//from w ww.j av a 2 s . c o m WebTopSession.UploadedFile uploadedFile = null; HashMap<String, String> multipartParams = new HashMap<>(); try { String service = ServletUtils.getStringParameter(request, "service", true); String cntx = ServletUtils.getStringParameter(request, "context", true); String tag = ServletUtils.getStringParameter(request, "tag", null); if (!ServletFileUpload.isMultipartContent(request)) throw new Exception("No upload request"); IServiceUploadStreamListener istream = getUploadStreamListener(cntx); if (istream != null) { try { MapItem data = new MapItem(); // Empty response data // Defines the upload object upload = new ServletFileUpload(); FileItemIterator it = upload.getItemIterator(request); while (it.hasNext()) { FileItemStream fis = it.next(); if (fis.isFormField()) { InputStream is = null; try { is = fis.openStream(); String key = fis.getFieldName(); String value = IOUtils.toString(is, "UTF-8"); multipartParams.put(key, value); } finally { IOUtils.closeQuietly(is); } } else { // Creates uploaded object uploadedFile = new WebTopSession.UploadedFile(true, service, IdentifierUtils.getUUID(), tag, fis.getName(), -1, findMediaType(fis)); // Fill response data data.add("virtual", uploadedFile.isVirtual()); data.add("editable", isFileEditableInDocEditor(fis.getName())); // Handle listener, its implementation can stop // file upload throwing a UploadException. InputStream is = null; try { getEnv().getSession().addUploadedFile(uploadedFile); is = fis.openStream(); istream.onUpload(cntx, request, multipartParams, uploadedFile, is, data); } finally { IOUtils.closeQuietly(is); getEnv().getSession().removeUploadedFile(uploadedFile, false); } } } new JsonResult(data).printTo(out); } catch (UploadException ex1) { new JsonResult(false, ex1.getMessage()).printTo(out); } catch (Exception ex1) { throw ex1; } } else { try { MapItem data = new MapItem(); // Empty response data IServiceUploadListener iupload = getUploadListener(cntx); // Defines the upload object DiskFileItemFactory factory = new DiskFileItemFactory(); //TODO: valutare come imporre i limiti //factory.setSizeThreshold(yourMaxMemorySize); //factory.setRepository(yourTempDirectory); upload = new ServletFileUpload(factory); List<FileItem> files = upload.parseRequest(request); // Plupload component (client-side) will upload multiple file // each in its own request. So we can skip loop on files. Iterator it = files.iterator(); while (it.hasNext()) { FileItem fi = (FileItem) it.next(); if (fi.isFormField()) { InputStream is = null; try { is = fi.getInputStream(); String key = fi.getFieldName(); String value = IOUtils.toString(is, "UTF-8"); multipartParams.put(key, value); } finally { IOUtils.closeQuietly(is); } } else { // Writes content into a temp file File file = WT.createTempFile(UPLOAD_TEMPFILE_PREFIX); fi.write(file); // Creates uploaded object uploadedFile = new WebTopSession.UploadedFile(false, service, file.getName(), tag, fi.getName(), fi.getSize(), findMediaType(fi)); getEnv().getSession().addUploadedFile(uploadedFile); // Fill response data data.add("virtual", uploadedFile.isVirtual()); data.add("uploadId", uploadedFile.getUploadId()); data.add("editable", isFileEditableInDocEditor(fi.getName())); // Handle listener (if present), its implementation can stop // file upload throwing a UploadException. if (iupload != null) { try { iupload.onUpload(cntx, request, multipartParams, uploadedFile, data); } catch (UploadException ex2) { getEnv().getSession().removeUploadedFile(uploadedFile, true); throw ex2; } } } } new JsonResult(data).printTo(out); } catch (UploadException ex1) { new JsonResult(ex1).printTo(out); } } } catch (Exception ex) { WebTopApp.logger.error("Error uploading", ex); new JsonResult(ex).printTo(out); } }
From source file:kg12.Ex12_2.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w . j a v a 2 s .c o 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.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet Ex12_2</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>???</h1>"); // multipart/form-data ?? if (ServletFileUpload.isMultipartContent(request)) { out.println("???<br>"); } else { out.println("?????<br>"); out.close(); return; } // ServletFileUpload?? DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload sfu = new ServletFileUpload(factory); // ??? int fileSizeMax = 1024000; factory.setSizeThreshold(1024); sfu.setSizeMax(fileSizeMax); sfu.setHeaderEncoding("UTF-8"); // ? String format = "%s:%s<br>%n"; // ??????? FileItemIterator fileIt = sfu.getItemIterator(request); while (fileIt.hasNext()) { FileItemStream item = fileIt.next(); if (item.isFormField()) { // out.print("<br>??<br>"); out.printf(format, "??", item.getFieldName()); InputStream is = item.openStream(); // ? byte ?? byte[] b = new byte[255]; // byte? b ???? is.read(b, 0, b.length); // byte? b ? "UTF-8" ??String??? result ? String result = new String(b, "UTF-8"); out.printf(format, "", result); } else { // out.print("<br>??<br>"); out.printf(format, "??", item.getName()); InputStream is = item.openStream(); String fileName = item.getName(); int len = 0; byte[] buffer = new byte[fileSizeMax]; FileOutputStream fos = new FileOutputStream( "D:\\NetBeansProjects\\ap2_www\\web\\kg12\\" + fileName); try { while ((len = is.read(buffer)) > 0) { fos.write(buffer, 0, len); } } finally { fos.close(); } } } out.println("</body>"); out.println("</html>"); } catch (FileUploadException e) { out.println(e + "<br>"); throw new ServletException(e); } catch (Exception e) { out.println(e + "<br>"); throw new ServletException(e); } finally { out.close(); } }
From source file:cn.webwheel.ActionSetter.java
@SuppressWarnings("unchecked") public Object[] set(Object action, ActionInfo ai, HttpServletRequest request) throws IOException { SetterConfig cfg = ai.getSetterConfig(); List<SetterInfo> setters; if (action != null) { Class cls = action.getClass(); setters = setterMap.get(cls);// www .j a va 2 s. co m if (setters == null) { synchronized (this) { setters = setterMap.get(cls); if (setters == null) { Map<Class, List<SetterInfo>> map = new HashMap<Class, List<SetterInfo>>(setterMap); map.put(cls, setters = parseSetters(cls)); setterMap = map; } } } } else { setters = Collections.emptyList(); } List<SetterInfo> args = argMap.get(ai.actionMethod); if (args == null) { synchronized (this) { args = argMap.get(ai.actionMethod); if (args == null) { Map<Method, List<SetterInfo>> map = new HashMap<Method, List<SetterInfo>>(argMap); map.put(ai.actionMethod, args = parseArgs(ai.actionMethod)); argMap = map; } } } if (setters.isEmpty() && args.isEmpty()) return new Object[0]; Map<String, Object> params; try { if (cfg.getCharset() != null) { request.setCharacterEncoding(cfg.getCharset()); } } catch (UnsupportedEncodingException e) { // } if (ServletFileUpload.isMultipartContent(request)) { params = new HashMap<String, Object>(request.getParameterMap()); request.setAttribute(WRPName, params); ServletFileUpload fileUpload = new ServletFileUpload(); if (cfg.getCharset() != null) { fileUpload.setHeaderEncoding(cfg.getCharset()); } if (cfg.getFileUploadSizeMax() != 0) { fileUpload.setSizeMax(cfg.getFileUploadSizeMax()); } if (cfg.getFileUploadFileSizeMax() != 0) { fileUpload.setFileSizeMax(cfg.getFileUploadFileSizeMax()); } boolean throwe = false; try { FileItemIterator it = fileUpload.getItemIterator(request); while (it.hasNext()) { FileItemStream fis = it.next(); if (fis.isFormField()) { String s = Streams.asString(fis.openStream(), cfg.getCharset()); Object o = params.get(fis.getFieldName()); if (o == null) { params.put(fis.getFieldName(), new String[] { s }); } else if (o instanceof String[]) { String[] ss = (String[]) o; String[] nss = new String[ss.length + 1]; System.arraycopy(ss, 0, nss, 0, ss.length); nss[ss.length] = s; params.put(fis.getFieldName(), nss); } } else if (!fis.getName().isEmpty()) { File tempFile; try { tempFile = File.createTempFile("wfu", null); } catch (IOException e) { throwe = true; throw e; } FileExImpl fileEx = new FileExImpl(tempFile); Object o = params.get(fis.getFieldName()); if (o == null) { params.put(fis.getFieldName(), new FileEx[] { fileEx }); } else if (o instanceof FileEx[]) { FileEx[] ss = (FileEx[]) o; FileEx[] nss = new FileEx[ss.length + 1]; System.arraycopy(ss, 0, nss, 0, ss.length); nss[ss.length] = fileEx; params.put(fis.getFieldName(), nss); } Streams.copy(fis.openStream(), new FileOutputStream(fileEx.getFile()), true); fileEx.fileName = fis.getName(); fileEx.contentType = fis.getContentType(); } } } catch (FileUploadException e) { if (action instanceof FileUploadExceptionAware) { ((FileUploadExceptionAware) action).setFileUploadException(e); } } catch (IOException e) { if (throwe) { throw e; } } } else { params = request.getParameterMap(); } if (cfg.getSetterPolicy() == SetterPolicy.ParameterAndField || (cfg.getSetterPolicy() == SetterPolicy.Auto && args.isEmpty())) { for (SetterInfo si : setters) { si.setter.set(action, si.member, params, si.paramName); } } Object[] as = new Object[args.size()]; for (int i = 0; i < as.length; i++) { SetterInfo si = args.get(i); as[i] = si.setter.set(action, null, params, si.paramName); } return as; }