List of usage examples for org.apache.commons.fileupload FileItem getContentType
String getContentType();
null
if not defined. From source file:fr.paris.lutece.plugins.form.business.EntryTypeFile.java
/** * save in the list of response the response associate to the entry in the form submit * @param request HttpRequest/*from w w w . j ava 2s . co m*/ * @param listResponse the list of response associate to the entry in the form submit * @param locale the locale * @return a Form error object if there is an error in the response */ public FormError getResponseData(HttpServletRequest request, List<Response> listResponse, Locale locale) { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; FileItem fileSource = multipartRequest.getFile(FormUtils.EMPTY_STRING + this.getIdEntry()); String strFilename = FileUploadService.getFileNameOnly(fileSource); List<RegularExpression> listRegularExpression = this.getFields().get(0).getRegularExpressionList(); Response response = new Response(); response.setEntry(this); if (this.isMandatory()) { if ((strFilename == null) || (strFilename.equals(EMPTY_STRING))) { FormError formError = new FormError(); formError.setMandatoryError(true); formError.setTitleQuestion(this.getTitle()); return formError; } } String strMimeType = fileSource.getContentType(); if ((strFilename != null) && (!strFilename.equals(EMPTY_STRING)) && (listRegularExpression != null) && (listRegularExpression.size() != 0) && RegularExpressionService.getInstance().isAvailable()) { for (RegularExpression regularExpression : listRegularExpression) { if (!RegularExpressionService.getInstance().isMatches(strMimeType, regularExpression)) { FormError formError = new FormError(); formError.setMandatoryError(false); formError.setTitleQuestion(this.getTitle()); formError.setErrorMessage(regularExpression.getErrorMessage()); return formError; } } } byte[] byValueEntry = fileSource.get(); response.setValueResponse(byValueEntry); response.setFileName(strFilename); response.setFileExtension(FilenameUtils.getExtension(strFilename)); listResponse.add(response); return null; }
From source file:Atualizar.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { boolean isMultipart = ServletFileUpload.isMultipartContent(req); String caminho;/*www . j av a 2s.c o m*/ if (isMultipart) { try { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = (List<FileItem>) upload.parseRequest(req); for (FileItem item : items) { if (item.isFormField()) { resp.getWriter() .println("No campo file" + this.getServletContext().getRealPath("/img")); resp.getWriter().println("Name campo: " + item.getFieldName()); resp.getWriter().println("Value campo: " + item.getString()); req.setAttribute(item.getFieldName(), item.getString()); } else { //caso seja um campo do tipo file resp.getWriter().println("Campo file"); resp.getWriter().println("Name:" + item.getFieldName()); resp.getWriter().println("nome arquivo :" + item.getName()); resp.getWriter().println("Size:" + item.getSize()); resp.getWriter().println("ContentType:" + item.getContentType()); resp.getWriter().println( "C:\\uploads" + File.separator + new Date().getTime() + "_" + item.getName()); if (item.getName() == "" || item.getName() == null) { caminho = this.getServletContext().getRealPath("\\img\\user.jpg"); } else { caminho = "img" + File.separator + new Date().getTime() + "_" + item.getName(); } resp.getWriter().println("Caminho: " + caminho); req.setAttribute("caminho", caminho); File uploadedFile = new File( "E:\\Documentos\\NetBeansProjects\\SisLivros\\web\\" + caminho); item.write(uploadedFile); req.setAttribute("caminho", caminho); // req.getRequestDispatcher("cadastrouser").forward(req, resp); } } } catch (Exception e) { resp.getWriter().println("ocorreu um problema ao fazer o upload: " + e.getMessage()); } } }
From source file:com.stratelia.webactiv.agenda.servlets.AgendaRequestRouter.java
private File processFormUpload(AgendaSessionController agendaSc, HttpServletRequest request) { String logicalName = ""; String tempFolderName = ""; String tempFolderPath = ""; String fileType = ""; long fileSize = 0; File fileUploaded = null;//from w ww. ja va2s . c om try { List<FileItem> items = HttpRequest.decorate(request).getFileItems(); FileItem fileItem = FileUploadUtil.getFile(items, "fileCalendar"); if (fileItem != null) { logicalName = fileItem.getName(); if (logicalName != null) { logicalName = logicalName.substring(logicalName.lastIndexOf(File.separator) + 1, logicalName.length()); // Name of temp folder: timestamp and userId tempFolderName = new Long(new Date().getTime()).toString() + "_" + agendaSc.getUserId(); // Mime type of the file fileType = fileItem.getContentType(); fileSize = fileItem.getSize(); // Directory Temp for the uploaded file tempFolderPath = FileRepositoryManager.getAbsolutePath(agendaSc.getComponentId()) + GeneralPropertiesManager.getString("RepositoryTypeTemp") + File.separator + tempFolderName; if (!new File(tempFolderPath).exists()) { FileRepositoryManager.createAbsolutePath(agendaSc.getComponentId(), GeneralPropertiesManager.getString("RepositoryTypeTemp") + File.separator + tempFolderName); } // Creation of the file in the temp folder fileUploaded = new File(FileRepositoryManager.getAbsolutePath(agendaSc.getComponentId()) + GeneralPropertiesManager.getString("RepositoryTypeTemp") + File.separator + tempFolderName + File.separator + logicalName); fileItem.write(fileUploaded); // Is a real file ? if (fileSize > 0) { SilverTrace.debug("agenda", "AgendaRequestRouter.processFormUpload()", "root.MSG_GEN_PARAM_VALUE", "fileUploaded = " + fileUploaded + " fileSize=" + fileSize + " fileType=" + fileType); } } } } catch (Exception e) { // Other exception SilverTrace.warn("agenda", "AgendaRequestRouter.processFormUpload()", "root.EX_LOAD_ATTACHMENT_FAILED", e); } return fileUploaded; }
From source file:com.amazonaws.serverless.proxy.internal.servlet.AwsProxyHttpServletRequest.java
private Map<String, Part> getMultipartFormParametersMap() { if (!ServletFileUpload.isMultipartContent(this)) { // isMultipartContent also checks the content type return new HashMap<>(); }//from ww w .j ava 2 s . c o m Map<String, Part> output = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); ServletFileUpload upload = new ServletFileUpload(); try { List<FileItem> items = upload.parseRequest(this); for (FileItem item : items) { AwsProxyRequestPart newPart = new AwsProxyRequestPart(item.get()); newPart.setName(item.getName()); newPart.setSubmittedFileName(item.getFieldName()); newPart.setContentType(item.getContentType()); newPart.setSize(item.getSize()); Iterator<String> headerNamesIterator = item.getHeaders().getHeaderNames(); while (headerNamesIterator.hasNext()) { String headerName = headerNamesIterator.next(); Iterator<String> headerValuesIterator = item.getHeaders().getHeaders(headerName); while (headerValuesIterator.hasNext()) { newPart.addHeader(headerName, headerValuesIterator.next()); } } output.put(item.getFieldName(), newPart); } } catch (FileUploadException e) { // TODO: Should we swallaw this? e.printStackTrace(); } return output; }
From source file:com.buddycloud.mediaserver.business.dao.MediaDAO.java
/** * Uploads media./*from w w w.j av 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:fr.paris.lutece.plugins.document.web.category.CategoryJspBean.java
/** * Create Category/*from ww w . jav a 2s . 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:eu.wisebed.wiseui.server.rpc.ImageUploadServiceImpl.java
/** * Override executeAction to save the received files in a custom place * and delete these items from session// www .j a v a2s . c o m */ @Override public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException { String response = ""; int cont = 0; for (FileItem item : sessionFiles) { if (false == item.isFormField()) { cont++; try { // Save a temporary file in the default system temp directory File uploadedFile = File.createTempFile("upload-", ".bin"); // write item to a file item.write(uploadedFile); // open and read content from file stream FileInputStream in = new FileInputStream(uploadedFile); byte fileContent[] = new byte[(int) uploadedFile.length()]; in.read(fileContent); // store content in persistance BinaryImage image = new BinaryImage(); image.setFileName(item.getName()); image.setFileSize(item.getSize()); image.setContent(fileContent); image.setContentType(item.getContentType()); LOGGER.info("Storing image: [Filename-> " + item.getName() + " ]"); persistenceService.storeBinaryImage(image); // Compose an xml message with the full file information // which can be parsed in client side response += "<file-" + cont + "-field>" + item.getFieldName() + "</file-" + cont + "-field>\n"; response += "<file-" + cont + "-name>" + item.getName() + "</file-" + cont + "-name>\n"; response += "<file-" + cont + "-size>" + item.getSize() + "</file-" + cont + "-size>\n"; response += "<file-" + cont + "-type>" + item.getContentType() + "</file-" + cont + "-type>\n"; } catch (Exception e) { throw new UploadActionException(e); } } } // Remove files from session because we have a copy of them removeSessionFileItems(request); // set the count of files response += "<file-count>" + cont + "</file-count>\n"; // Send information of the received files to the client return "<response>\n" + response + "</response>\n"; }
From source file:gwtuploadsample.server.SampleUploadServlet.java
/** * Override executeAction to save the received files in a custom place * and delete this items from session.//from w ww . j a v a2 s . co m */ @Override public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException { String response = ""; int cont = 0; for (FileItem item : sessionFiles) { if (false == item.isFormField()) { cont++; try { /// Create a new file based on the remote file name in the client // String saveName = item.getName().replaceAll("[\\\\/><\\|\\s\"'{}()\\[\\]]+", "_"); // File file =new File("/tmp/" + saveName); /// Create a temporary file placed in /tmp (only works in unix) // File file = File.createTempFile("upload-", ".bin", new File("/tmp")); /// Create a temporary file placed in the default system temp folder File file = File.createTempFile("upload-", ".bin"); item.write(file); /// Save a list with the received files receivedFiles.put(item.getFieldName(), file); receivedContentTypes.put(item.getFieldName(), item.getContentType()); /// Compose a xml message with the full file information response += "<file-" + cont + "-field>" + item.getFieldName() + "</file-" + cont + "-field>\n"; response += "<file-" + cont + "-name>" + item.getName() + "</file-" + cont + "-name>\n"; response += "<file-" + cont + "-size>" + item.getSize() + "</file-" + cont + "-size>\n"; response += "<file-" + cont + "-type>" + item.getContentType() + "</file-" + cont + "type>\n"; } catch (Exception e) { throw new UploadActionException(e); } } } /// Remove files from session because we have a copy of them removeSessionFileItems(request); /// Send information of the received files to the client. return "<response>\n" + response + "</response>\n"; }
From source file:dk.clarin.tools.userhandle.java
public static String getParmFromMultipartFormData(HttpServletRequest request, List<FileItem> items, String parm) {//from w w w .j a v a 2 s .c o m logger.debug("parm:[" + parm + "]"); String userHandle = ""; boolean is_multipart_formData = ServletFileUpload.isMultipartContent(request); if (is_multipart_formData) { try { /* logger.debug("In try"); DiskFileItemFactory fileItemFactory = new DiskFileItemFactory (); / * *Set the size threshold, above which content will be stored on disk. * / fileItemFactory.setSizeThreshold(1*1024*1024); //1 MB / * * Set the temporary directory to store the uploaded files of size above threshold. * / logger.debug("making tmpDir in " + ToolsProperties.tempdir); File tmpDir = new File(ToolsProperties.tempdir); if(!tmpDir.isDirectory()) { logger.debug("!tmpDir.isDirectory()"); throw new ServletException("Trying to set \"" + ToolsProperties.tempdir + "\" as temporary directory, but this is not a valid directory."); } fileItemFactory.setRepository(tmpDir); * / ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); logger.debug("Now uploadHandler.parseRequest"); List items<FileItem> = uploadHandler.parseRequest(request); */ logger.debug("items:" + items); Iterator<FileItem> itr = items.iterator(); logger.debug("itr:" + itr); while (itr.hasNext()) { logger.debug("in loop"); FileItem item = (FileItem) itr.next(); /* * Handle Form Fields. */ if (item.isFormField()) { logger.debug("Field Name = " + item.getFieldName() + ", String = " + item.getString()); if (item.getFieldName().equals(parm)) { userHandle = item.getString(); logger.debug("Found " + parm + " = " + userHandle); /* if(userId == null && userHandle != null) userId = userhandle.getUserId(request,userHandle); if(userEmail == null && userId != null) userEmail = userhandle.getEmailAddress(request,userHandle,userId); */ break; // currently not interested in other fields than parm } } else if (item.getName() != "") { /* * Write file to the ultimate location. */ logger.debug("File = " + item.getName()); /* We don't handle file upload here data = item.getName(); File file = new File(destinationDir,item.getName()); item.write(file); */ logger.debug("FieldName = " + item.getFieldName()); logger.debug("Name = " + item.getName()); logger.debug("ContentType = " + item.getContentType()); logger.debug("Size = " + item.getSize()); logger.debug("DestinationDir = " + ToolsProperties.documentRoot /*+ ToolsProperties.stagingArea*/); } } } catch (Exception ex) { logger.error("uploadHandler.parseRequest Exception"); } } else { @SuppressWarnings("unchecked") Enumeration<String> parmNames = (Enumeration<String>) request.getParameterNames(); for (Enumeration<String> e = parmNames; e.hasMoreElements();) { // Well, you don't get here AT ALL if enctype='multipart/form-data' String parmName = e.nextElement(); logger.debug("parmName:" + parmName); String vals[] = request.getParameterValues(parmName); for (int j = 0; j < vals.length; ++j) { logger.debug("val:" + vals[j]); } } } logger.debug("value[" + parm + "]=" + userHandle); return userHandle; }
From source file:com.dien.upload.server.UploadServlet.java
/** * Get an uploaded file item./*w w w. j ava 2s .c om*/ * * @param request * @param response * @throws IOException */ public void getUploadedFile(HttpServletRequest request, HttpServletResponse response) throws IOException { String parameter = request.getParameter(UConsts.PARAM_SHOW); FileItem item = findFileItem(getSessionFileItems(request), parameter); if (item != null) { logger.debug("UPLOAD-SERVLET (" + request.getSession().getId() + ") getUploadedFile: " + parameter + " returning: " + item.getContentType() + ", " + item.getName() + ", " + item.getSize() + " bytes"); response.setContentType(item.getContentType()); copyFromInputStreamToOutputStream(item.getInputStream(), response.getOutputStream()); } else { logger.info("UPLOAD-SERVLET (" + request.getSession().getId() + ") getUploadedFile: " + parameter + " file isn't in session."); renderJSONResponse(request, response, XML_ERROR_ITEM_NOT_FOUND); } }