List of usage examples for org.apache.commons.fileupload FileItemStream getName
String getName();
From source file:com.github.thorqin.webapi.FileManager.java
public List<FileInfo> saveUploadFiles(HttpServletRequest request, int maxSize) throws ServletException, IOException, FileUploadException { List<FileInfo> uploadList = new LinkedList<>(); request.setCharacterEncoding("utf-8"); ServletFileUpload upload = new ServletFileUpload(); upload.setHeaderEncoding("UTF-8"); if (!ServletFileUpload.isMultipartContent(request)) { return uploadList; }/* w w w. java2 s . c om*/ upload.setSizeMax(maxSize); FileItemIterator iter; iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); try (InputStream stream = item.openStream()) { if (!item.isFormField()) { FileInfo info = new FileInfo(); info.setFileName(item.getName()); if (getFileMIME(info.getExtName()) == null) { logger.log(Level.WARNING, "Upload file's MIME type isn't permitted."); continue; } info = store(stream, info.fileName); uploadList.add(info); } } } return uploadList; }
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 {//from ww w .jav a 2s . co m // 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:com.medallia.spider.api.DynamicInputImpl.java
/** * Creates a new {@link DynamicInputImpl} * @param request from which to read the request parameters *///from ww w .j a v a 2s. c om public DynamicInputImpl(HttpServletRequest request) { @SuppressWarnings("unchecked") Map<String, String[]> reqParams = Maps.newHashMap(request.getParameterMap()); this.inputParams = reqParams; if (ServletFileUpload.isMultipartContent(request)) { this.fileUploads = Maps.newHashMap(); Multimap<String, String> inputParamsWithList = ArrayListMultimap.create(); ServletFileUpload upload = new ServletFileUpload(); try { FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String fieldName = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { inputParamsWithList.put(fieldName, Streams.asString(stream, Charsets.UTF_8.name())); } else { final String filename = item.getName(); final byte[] bytes = ByteStreams.toByteArray(stream); fileUploads.put(fieldName, new UploadedFile() { @Override public String getFilename() { return filename; } @Override public byte[] getBytes() { return bytes; } @Override public int getSize() { return bytes.length; } }); } } for (Entry<String, Collection<String>> entry : inputParamsWithList.asMap().entrySet()) { inputParams.put(entry.getKey(), entry.getValue().toArray(new String[0])); } } catch (IOException | FileUploadException e) { throw new IllegalArgumentException("Failed to parse multipart", e); } } else { this.fileUploads = Collections.emptyMap(); } }
From source file:com.github.thorqin.toolkit.web.utility.UploadManager.java
/** * Save upload file to disk/*from w w w . ja va 2s . co m*/ * @param request HttpServletRequest * @param maxSize maximum size of the upload file, in bytes. * @return Saved file info list * @throws ServletException * @throws IOException * @throws FileUploadException */ public List<FileInfo> saveUploadFiles(HttpServletRequest request, int maxSize) throws ServletException, IOException, FileUploadException { List<FileInfo> uploadList = new LinkedList<>(); request.setCharacterEncoding("utf-8"); ServletFileUpload upload = new ServletFileUpload(); upload.setHeaderEncoding("UTF-8"); if (!ServletFileUpload.isMultipartContent(request)) { return uploadList; } upload.setSizeMax(maxSize); FileItemIterator iterator = upload.getItemIterator(request); while (iterator.hasNext()) { FileItemStream item = iterator.next(); try (InputStream stream = item.openStream()) { if (!item.isFormField()) { FileInfo info = new FileInfo(); info.setFileName(item.getName()); if (pattern != null && !pattern.matcher(info.fileName).matches()) { continue; } info = store(stream, info.fileName); uploadList.add(info); } } } return uploadList; }
From source file:com.threewks.thundr.bind.http.MultipartHttpBinder.java
void extractParameters(HttpServletRequest req, Map<String, List<String>> formFields, Map<String, MultipartFile> fileFields) { try {// www .j av a 2 s.co m FileItemIterator itemIterator = upload.getItemIterator(req); while (itemIterator.hasNext()) { FileItemStream item = itemIterator.next(); InputStream stream = item.openStream(); String fieldName = item.getFieldName(); if (item.isFormField()) { List<String> existing = formFields.get(fieldName); if (existing == null) { existing = new LinkedList<String>(); formFields.put(fieldName, existing); } existing.add(Streams.readString(stream)); } else { MultipartFile file = new MultipartFile(item.getName(), Streams.readBytes(stream), item.getContentType()); fileFields.put(fieldName, file); } stream.close(); } } catch (Exception e) { throw new BindException(e, "Failed to bind multipart form data: %s", e.getMessage()); } }
From source file:lucee.runtime.type.scope.FormImpl.java
private void initializeMultiPart(PageContext pc, boolean scriptProteced) { // get temp directory Resource tempDir = ((ConfigImpl) pc.getConfig()).getTempDirectory(); Resource tempFile;// ww w . jav a 2s . c o m // Create a new file upload handler final String encoding = getEncoding(); FileItemFactory factory = tempDir instanceof File ? new DiskFileItemFactory(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD, (File) tempDir) : new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding(encoding); //ServletRequestContext c = new ServletRequestContext(pc.getHttpServletRequest()); HttpServletRequest req = pc.getHttpServletRequest(); ServletRequestContext context = new ServletRequestContext(req) { public String getCharacterEncoding() { return encoding; } }; // Parse the request try { FileItemIterator iter = upload.getItemIterator(context); //byte[] value; InputStream is; ArrayList<URLItem> list = new ArrayList<URLItem>(); while (iter.hasNext()) { FileItemStream item = iter.next(); is = IOUtil.toBufferedInputStream(item.openStream()); if (item.getContentType() == null || StringUtil.isEmpty(item.getName())) { list.add(new URLItem(item.getFieldName(), new String(IOUtil.toBytes(is), encoding), false)); } else { tempFile = tempDir.getRealResource(getFileName()); fileItems.put(item.getFieldName().toLowerCase(), new Item(tempFile, item.getContentType(), item.getName(), item.getFieldName())); String value = tempFile.toString(); IOUtil.copy(is, tempFile, true); list.add(new URLItem(item.getFieldName(), value, false)); } } raw = list.toArray(new URLItem[list.size()]); fillDecoded(raw, encoding, scriptProteced, pc.getApplicationContext().getSameFieldAsArray(SCOPE_FORM)); } catch (Exception e) { //throw new PageRuntimeException(Caster.toPageException(e)); fillDecodedEL(new URLItem[0], encoding, scriptProteced, pc.getApplicationContext().getSameFieldAsArray(SCOPE_FORM)); initException = e; } }
From source file:com.pronoiahealth.olhie.server.rest.BooklogoUploadServiceImpl.java
@Override @POST//from w w w.j a va 2 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:fi.iki.elonen.SimpleWebServer.java
private Response getUploadMsgAndExec(IHTTPSession session) throws FileUploadException, IOException { uploader = new NanoFileUpload(new DiskFileItemFactory()); files = new HashMap<String, List<FileItem>>(); FileItemIterator iter = uploader.getItemIterator(session); String fileName = "", newFileName = ""; try {//from w ww. j a va 2s .c om while (iter.hasNext()) { FileItemStream item = iter.next(); fileName = item.getName(); newFileName = rootDirs.get(0) + "/".concat(fileName); FileItem fileItem = uploader.getFileItemFactory().createItem(item.getFieldName(), item.getContentType(), item.isFormField(), newFileName); files.put(fileItem.getFieldName(), Arrays.asList(new FileItem[] { fileItem })); try { Streams.copy(item.openStream(), (new FileOutputStream(newFileName)), true); } catch (Exception e) { System.err.println(e.getMessage()); } fileItem.setHeaders(item.getHeaders()); } } catch (FileUploadException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return newFixedLengthResponse( "<html><body> \n File: " + fileName + " upload to " + newFileName + "! \n </body></html>\n"); }
From source file:it.polimi.modaclouds.cloudapp.mic.servlet.RegisterServlet.java
private void parseReq(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { try {//from w w w .j av a 2 s . c o m MF mf = MF.getFactory(); req.setCharacterEncoding("UTF-8"); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iterator = upload.getItemIterator(req); HashMap<String, String> map = new HashMap<String, String>(); while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream stream = item.openStream(); if (item.isFormField()) { String field = item.getFieldName(); String value = Streams.asString(stream); map.put(field, value); stream.close(); } else { String filename = item.getName(); String[] extension = filename.split("\\."); String mail = map.get("mail"); if (mail != null) { filename = mail + "_" + String.valueOf(filename.hashCode()) + "." + extension[extension.length - 1]; } else { filename = String.valueOf(filename.hashCode()) + "." + extension[extension.length - 1]; } map.put("filename", filename); byte[] buffer = IOUtils.toByteArray(stream); mf.getBlobManagerFactory().createCloudBlobManager().uploadBlob(buffer, filename); stream.close(); } } String email = map.get("mail"); String firstName = map.get("firstName"); String lastName = map.get("lastName"); String dayS = map.get("day"); String monthS = map.get("month"); String yearS = map.get("year"); String password = map.get("password"); String filename = map.get("filename"); String date = yearS + "-" + monthS + "-" + dayS; char gender = map.get("gender").charAt(0); RequestDispatcher disp; Connection c = mf.getSQLService().getConnection(); String stm = "INSERT INTO UserProfile VALUES('" + email + "', '" + password + "', '" + firstName + "', '" + lastName + "', '" + date + "', '" + gender + "', '" + filename + "')"; Statement statement = c.createStatement(); statement.executeUpdate(stm); statement.close(); c.close(); req.getSession(true).setAttribute("actualUser", email); req.getSession(true).setAttribute("edit", "false"); disp = req.getRequestDispatcher("SelectTopic.jsp"); disp.forward(req, response); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } catch (FileUploadException e) { e.printStackTrace(); } }
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 .jav a2 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; }