List of usage examples for org.apache.commons.fileupload FileItem get
byte[] get();
From source file:gwtupload.sendmailsample.server.SendMailSampleServlet.java
@Override public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException { try {/*from w w w .j a v a2 s. c om*/ String from = null, to = null, subject = "", body = ""; // create a new multipart content MimeMultipart multiPart = new MimeMultipart(); for (FileItem item : sessionFiles) { if (item.isFormField()) { if ("from".equals(item.getFieldName())) from = item.getString(); if ("to".equals(item.getFieldName())) to = item.getString(); if ("subject".equals(item.getFieldName())) subject = item.getString(); if ("body".equals(item.getFieldName())) body = item.getString(); } else { // add the file part to multipart content MimeBodyPart part = new MimeBodyPart(); part.setFileName(item.getName()); part.setDataHandler( new DataHandler(new ByteArrayDataSource(item.get(), item.getContentType()))); multiPart.addBodyPart(part); } } // add the text part to multipart content MimeBodyPart txtPart = new MimeBodyPart(); txtPart.setContent(body, "text/plain"); multiPart.addBodyPart(txtPart); // configure smtp server Properties props = System.getProperties(); props.put("mail.smtp.host", SMTP_SERVER); // create a new mail session and the mime message MimeMessage mime = new MimeMessage(Session.getInstance(props)); mime.setText(body); mime.setContent(multiPart); mime.setSubject(subject); mime.setFrom(new InternetAddress(from)); for (String rcpt : to.split("[\\s;,]+")) mime.addRecipient(Message.RecipientType.TO, new InternetAddress(rcpt)); // send the message Transport.send(mime); } catch (MessagingException e) { throw new UploadActionException(e.getMessage()); } return "Your mail has been sent successfuly."; }
From source file:fr.paris.lutece.plugins.directory.business.EntryTypeImg.java
/** * {@inheritDoc}//from w w w. j ava 2 s. c om */ @Override protected void checkRecordFieldData(FileItem fileItem, Locale locale) throws DirectoryErrorException { String strFilename = (fileItem != null) ? FileUploadService.getFileNameOnly(fileItem) : StringUtils.EMPTY; BufferedImage image = null; try { if ((fileItem != null) && (fileItem.get() != null)) { image = ImageIO.read(new ByteArrayInputStream(fileItem.get())); } } catch (IOException e) { AppLogService.error(e); } if ((image == null) && StringUtils.isNotBlank(strFilename)) { String strErrorMessage = I18nService.getLocalizedString(MESSAGE_ERROR_NOT_AN_IMAGE, locale); throw new DirectoryErrorException(this.getTitle(), strErrorMessage); } }
From source file:com.jkingii.web.files.upload.java
/** * Processes requests for both HTTP//from w w w.ja va 2 s . c o m * <code>GET</code> and * <code>POST</code> methods. * * @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 { // Check that we have a file upload request isMultipart = ServletFileUpload.isMultipartContent(request); FileDataBase fdb = null; response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { CSession cSession = (CSession) request.getSession().getAttribute("cSession"); if (!isMultipart) { out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); out.println("<p>No file uploaded</p>"); out.println("</body>"); out.println("</html>"); return; } DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. factory.setRepository(new File(tempDir)); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Se verifica si el usuario tiene permisos de escritura. ColumnasPermisos permiso = checkPermisos(request, fileItems, out); if (permiso == null) { return; } // Process the uploaded file items Iterator i = fileItems.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); MessageDigest md5 = MessageDigest.getInstance("MD5"); if (!fi.isFormField()) { // Get the uploaded file parameters logger.info("Prosess Request: obteniendo session: [" + cSession + "] jsessionid = [" + request.getSession().getId() + "]", this); fdb = new FileDataBase(GenKey.newKey(), cSession.getAccessInfo().getEmpresa(), cSession.getAccessInfo().getUserInfo(), new Date().getTime(), fi.getName(), new MimeType().factory().getMime(fi.getName(), fi.get()), fi.get(), Hexadecimal.getHex(md5.digest(fi.get())), fi.getSize(), permiso); fileDataBaseFacade.create(fdb); } } ResponseConfig config = new ResponseConfig(); config.setTimeZone(cSession.getAccessInfo().getTimeZone()); out.println(fdb.toJson(config)); } catch (FileUploadException | NoSuchAlgorithmException e) { logger.error("Error cargando el fichero en el servidor, " + "Exception: {}", e.getMessage()); } catch (UnknownColumnException e) { logger.error("Imposible la columna para el link debe existir referer[{}], " + "p[{}]", request.getHeader("referer"), request.getParameter(PERMISO_FIELD)); logger.debug("referrer: " + request.getHeader("referrer")); } finally { out.close(); } }
From source file:fr.paris.lutece.plugins.document.web.category.CategoryJspBean.java
/** * Create Category// www.j a v a2 s.c o m * @param request The HTTP request * @return String The url page */ public String doCreateCategory(HttpServletRequest request) { Category category = new Category(); String strCategoryName = request.getParameter(PARAMETER_CATEGORY_NAME).trim(); String strCategoryDescription = request.getParameter(PARAMETER_CATEGORY_DESCRIPTION).trim(); String strWorkgroup = request.getParameter(PARAMETER_WORKGROUP_KEY); MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request; FileItem item = mRequest.getFile(PARAMETER_IMAGE_CONTENT); // Mandatory field if ((strCategoryName.length() == 0) || (strCategoryDescription.length() == 0)) { return AdminMessageService.getMessageUrl(request, Messages.MANDATORY_FIELDS, AdminMessage.TYPE_STOP); } // check if category exist if (CategoryHome.findByName(strCategoryName).size() > 0) { return AdminMessageService.getMessageUrl(request, MESSAGE_CATEGORY_EXIST, AdminMessage.TYPE_STOP); } category.setName(strCategoryName); category.setDescription(strCategoryDescription); byte[] bytes = item.get(); category.setIconContent(bytes); category.setIconMimeType(item.getContentType()); category.setWorkgroup(strWorkgroup); CategoryHome.create(category); return getHomeUrl(request); }
From source file:com.aliasi.demo.framework.DemoServlet.java
void generateOutput(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { InputStream in = null;//from w w w . j a va2 s . c o m OutputStream out = null; try { response.setContentType(mDemo.responseType()); out = response.getOutputStream(); @SuppressWarnings("unchecked") // bad inherited API from commons Properties properties = mapToProperties((Map<String, String[]>) request.getParameterMap()); String reqContentType = request.getContentType(); if (reqContentType == null || reqContentType.startsWith("text/plain")) { properties.setProperty("inputType", "text/plain"); String reqCharset = request.getCharacterEncoding(); if (reqCharset != null) properties.setProperty("inputCharset", reqCharset); in = request.getInputStream(); } else if (reqContentType.startsWith("application/x-www-form-urlencoded")) { String codedText = request.getParameter("inputText"); byte[] bytes = codedText.getBytes("ISO-8859-1"); in = new ByteArrayInputStream(bytes); } else if (ServletFileUpload.isMultipartContent(new ServletRequestContext(request))) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload uploader = new ServletFileUpload(factory); @SuppressWarnings("unchecked") // bad commons API List<FileItem> items = (List<FileItem>) uploader.parseRequest(request); Iterator<FileItem> it = items.iterator(); while (it.hasNext()) { log("found item"); FileItem item = it.next(); if (item.isFormField()) { String key = item.getFieldName(); String val = item.getString(); properties.setProperty(key, val); } else { byte[] bytes = item.get(); in = new ByteArrayInputStream(bytes); } } } else { System.out.println("unexpected content type"); String msg = "Unexpected request content" + reqContentType; throw new ServletException(msg); } mDemo.process(in, out, properties); } catch (FileUploadException e) { throw new ServletException(e); } finally { Streams.closeQuietly(in); Streams.closeQuietly(out); } }
From source file:com.buddycloud.mediaserver.business.dao.MediaDAO.java
/** * Uploads media.//from w w w . j a v a 2s .c o m * @param userId user that is uploading the media. * @param entityId channel where the media will belong. * @param request media file and required upload fields. * @param isAvatar if the media to be uploaded is an avatar. * @return media's metadata, if the upload ends with success * @throws FileUploadException the is something wrong with the request. * @throws UserNotAllowedException the user {@link userId} is now allowed to upload media in this channel. */ public String insertFormDataMedia(String userId, String entityId, Request request, boolean isAvatar) throws FileUploadException, UserNotAllowedException { LOGGER.debug("User '" + userId + "' trying to upload form-data media in: " + entityId); boolean isUserAllowed = pubsub.matchUserCapability(userId, entityId, new OwnerDecorator(new ModeratorDecorator(new PublisherDecorator()))); if (!isUserAllowed) { LOGGER.debug("User '" + userId + "' not allowed to upload file in: " + entityId); throw new UserNotAllowedException(userId); } DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold( Integer.valueOf(configuration.getProperty(MediaServerConfiguration.MEDIA_SIZE_LIMIT_PROPERTY))); List<FileItem> items = null; try { RestletFileUpload upload = new RestletFileUpload(factory); items = upload.parseRequest(request); } catch (Throwable e) { throw new FileUploadException("Invalid request data."); } // get form fields String fileName = getFormFieldContent(items, Constants.NAME_FIELD); String title = getFormFieldContent(items, Constants.TITLE_FIELD); String description = getFormFieldContent(items, Constants.DESC_FIELD); String contentType = getFormFieldContent(items, Constants.TYPE_FIELD); FileItem fileField = getFileFormField(items); if (fileField == null) { throw new FileUploadException("Must provide the file data."); } byte[] dataArray = fileField.get(); if (contentType == null) { if (fileField.getContentType() != null) { contentType = fileField.getContentType(); } else { throw new FileUploadException("Must provide a " + Constants.TYPE_FIELD + " for the uploaded file."); } } // storing Media media = storeMedia(fileName, title, description, XMPPUtils.getBareId(userId), entityId, contentType, dataArray, isAvatar); LOGGER.debug("Media sucessfully added. Media ID: " + media.getId()); return gson.toJson(media); }
From source file:com.wakasta.tubes2.AddProductPost.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String item_data = ""; // Check that we have a file upload request isMultipart = ServletFileUpload.isMultipartContent(request); response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); if (!isMultipart) { out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); out.println("<p>No file uploaded</p>"); out.println("</body>"); out.println("</html>"); return;//from w w w . jav a2 s .c om } DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. factory.setRepository(new File("c:\\temp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); try { // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); String fileName = fi.getName(); String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); // Write the file if (fileName.lastIndexOf("\\") >= 0) { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\"))); } else { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1)); } item_data = Base64.encodeBase64String(fi.get()); fi.write(file); // out.println("Uploaded Filename: " + fileName + "<br>"); // out.println(file); } } out.println("</body>"); out.println("</html>"); } catch (FileUploadException ex) { Logger.getLogger(AddProductPost.class.getName()).log(Level.SEVERE, null, ex); } catch (java.lang.Exception ex) { Logger.getLogger(AddProductPost.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:fr.paris.lutece.plugins.calendar.web.CalendarCategoryJspBean.java
/** * Create Category//from w w w.j av a2 s.c om * @param request The HTTP request * @return String The url page * @throws AccessDeniedException If the user is not allowed to access this * feature */ public String doCreateCategory(HttpServletRequest request) throws AccessDeniedException { if (!RBACService.isAuthorized(CalendarResourceIdService.RESOURCE_TYPE, RBAC.WILDCARD_RESOURCES_ID, CalendarResourceIdService.PERMISSION_MANAGE, getUser())) { throw new AccessDeniedException(); } Category category = new Category(); String strCategoryName = request.getParameter(PARAMETER_CATEGORY_NAME); String strCategoryDescription = request.getParameter(PARAMETER_CATEGORY_DESCRIPTION); String strWorkgroup = request.getParameter(PARAMETER_WORKGROUP_KEY); MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request; FileItem item = mRequest.getFile(PARAMETER_IMAGE_CONTENT); // Mandatory field if (strCategoryName.length() == 0) { return AdminMessageService.getMessageUrl(request, Messages.MANDATORY_FIELDS, AdminMessage.TYPE_STOP); } Plugin plugin = PluginService.getPlugin(Constants.PLUGIN_NAME); // check if category exist if (CategoryHome.findByName(strCategoryName, plugin).size() > 0) { return AdminMessageService.getMessageUrl(request, MESSAGE_CATEGORY_EXIST, AdminMessage.TYPE_STOP); } category.setName(strCategoryName); category.setDescription(strCategoryDescription); byte[] bytes = item.get(); category.setIconContent(bytes); category.setIconMimeType(item.getContentType()); category.setWorkgroup(strWorkgroup); CategoryHome.create(category, plugin); return AppPathService.getBaseUrl(request) + JSP_URL_CATEGORY_LIST; }
From source file:com.alkacon.opencms.excelimport.CmsResourceExcelImport.java
/** * Sets content from uploaded file.<p> * /*from w w w . j a v a2s . co m*/ * @param content the parameter value is only necessary for calling this method */ public void setParamExcelContent(String content) { // use parameter value if (content == null) { // do nothing } // get the file item from the multipart request if (getMultiPartFileItems() != null) { Iterator i = getMultiPartFileItems().iterator(); FileItem fi = null; while (i.hasNext()) { fi = (FileItem) i.next(); if (fi.getFieldName().equals(PARAM_EXCEL_FILE)) { // found the file objectif (fi != null) { long size = fi.getSize(); long maxFileSizeBytes = OpenCms.getWorkplaceManager().getFileBytesMaxUploadSize(getCms()); // check file size if ((maxFileSizeBytes > 0) && (size > maxFileSizeBytes)) { // file size is larger than maximum allowed file size, throw an error //throw new CmsWorkplaceException(); } m_excelContent = fi.get(); m_excelName = fi.getName(); fi.delete(); } else { continue; } } } }
From source file:edu.fullerton.ldvservlet.Upload.java
private int addFile(FileItem item, HashMap<String, String> params, Page vpage, String userName, ImageTable imageTable) throws ServletException { int ret = 0;//from w w w .j av a2 s. c om String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); if (sizeInBytes >= 100 && !fileName.isEmpty()) { Matcher m = fileNumPat.matcher(fieldName); if (m.find()) { String descriptionName = "desc" + m.group(1); String description = params.get(descriptionName); description = description == null ? "" : description; if (isValid(contentType)) { try { byte[] buf = item.get(); ByteArrayInputStream bis = new ByteArrayInputStream(buf); int imgId = imageTable.addImg(userName, bis, contentType); if (!description.isEmpty()) { imageTable.addDescription(imgId, description); } ret = imgId; vpage.add("uploaded " + fileName + " - " + description); vpage.addBlankLines(1); } catch (IOException | SQLException | NoSuchAlgorithmException ex) { String ermsg = "Error reading data for " + fileName + ex.getClass().getSimpleName() + " " + ex.getLocalizedMessage(); vpage.add(ermsg); vpage.addBlankLines(1); } } else { vpage.add(String.format("The file: %1$s has an unsuported mime type: %2$s", fileName, contentType)); vpage.addBlankLines(1); } } } return ret; }