List of usage examples for org.apache.commons.fileupload FileItem getContentType
String getContentType();
null
if not defined. From source file:com.tasktop.c2c.server.internal.wiki.server.WikiServiceController.java
@Section(value = "Attachments") @Title("Upload Attachment") @Secured({ Role.Community, Role.User, Role.Admin }) @RequestMapping(value = "{pageId}/attachment", method = RequestMethod.POST) public void uploadAttachment(@PathVariable(value = "pageId") Integer pageId, HttpServletRequest request, HttpServletResponse response) throws IOException, FileUploadException, TextHtmlContentExceptionWrapper { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<Attachment> attachments = new ArrayList<Attachment>(); Map<String, String> formValues = new HashMap<String, String>(); PageHandle pageHandle = new PageHandle(pageId); try {/*from w ww. ja v a2 s.c om*/ // find all existing attachments List<Attachment> allPageAttachments = service.listAttachments(pageId); // map them by name Map<String, Attachment> attachmentByName = new HashMap<String, Attachment>(); for (Attachment attachment : allPageAttachments) { attachmentByName.put(attachment.getName(), attachment); } // inspect the request, getting all posted attachments @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { formValues.put(item.getFieldName(), item.getString()); } else { Attachment attachment = new Attachment(); attachment.setPage(pageHandle); attachment.setContent(item.get()); attachment.setName(item.getName()); attachment.setMimeType(item.getContentType()); attachments.add(attachment); } } // for each new attachment, either create or update for (Attachment attachment : attachments) { Attachment attach = attachmentByName.get(attachment.getName()); if (attach != null) { attachment.setId(attach.getId()); service.updateAttachment(attachment); } else { service.createAttachment(attachment); } } // get content for response allPageAttachments = service.listAttachments(pageId); Page page = service.retrievePage(pageId); page.setContent(null); response.setContentType("text/html"); response.getWriter().write(jsonMapper.writeValueAsString( Collections.singletonMap("uploadResult", new UploadResult(page, allPageAttachments)))); } catch (Exception e) { throw new TextHtmlContentExceptionWrapper(e.getMessage(), e); } }
From source file:com.dien.upload.server.UploadServlet.java
protected Map<String, String> getFileItemsSummary(HttpServletRequest request, Map<String, String> ret) { if (ret == null) { ret = new HashMap<String, String>(); }//from w w w . ja v a 2 s. c om @SuppressWarnings("unchecked") List<FileItem> s = (List<FileItem>) request.getSession().getAttribute(SESSION_LAST_FILES); if (s != null) { for (FileItem i : s) { if (false == i.isFormField()) { ret.put("ctype", i.getContentType() != null ? i.getContentType() : "unknown"); ret.put("size", "" + i.getSize()); ret.put("name", "" + i.getName()); ret.put("field", "" + i.getFieldName()); } } ret.put(TAG_FINISHED, "ok"); } return ret; }
From source file:com.gwtcx.server.servlet.FileUploadServlet.java
@SuppressWarnings("rawtypes") private void processFiles(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // set the size threshold, above which content will be stored on disk factory.setSizeThreshold(1 * 1024 * 1024); // 1 MB // set the temporary directory (this is where files that exceed the threshold will be stored) factory.setRepository(tmpDir);//from w w w . j ava 2 s .c om // create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); try { String recordType = "Account"; // parse the request List items = upload.parseRequest(request); // process the uploaded items Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); // process a regular form field if (item.isFormField()) { Log.debug("Field Name: " + item.getFieldName() + ", Value: " + item.getString()); if (item.getFieldName().equals("recordType")) { recordType = item.getString(); } } else { // process a file upload Log.debug("Field Name: " + item.getFieldName() + ", Value: " + item.getName() + ", Content Type: " + item.getContentType() + ", In Memory: " + item.isInMemory() + ", File Size: " + item.getSize()); // write the uploaded file to the application's file staging area File file = new File(destinationDir, item.getName()); item.write(file); // import the CSV file importCsvFile(recordType, file.getPath()); // file.delete(); // TO DO } } } catch (FileUploadException e) { Log.error("Error encountered while parsing the request", e); } catch (Exception e) { Log.error("Error encountered while uploading file", e); } }
From source file:fr.paris.lutece.plugins.directory.business.EntryTypeDownloadUrl.java
/** * {@inheritDoc}//from w w w. j a va 2 s . c o m */ @Override public void getRecordFieldData(Record record, HttpServletRequest request, boolean bTestDirectoryError, boolean bAddNewValue, List<RecordField> listRecordField, Locale locale) throws DirectoryErrorException { if (request instanceof MultipartHttpServletRequest) { // Check if the BlobStoreClientService is available DirectoryAsynchronousUploadHandler handler = DirectoryAsynchronousUploadHandler.getHandler(); if (!handler.isBlobStoreClientServiceAvailable()) { String strErrorMessage = I18nService .getLocalizedString(MESSAGE_BLOBSTORE_CLIENT_SERVICE_UNAVAILABLE, locale); throw new DirectoryErrorException(this.getTitle(), strErrorMessage); } // Get entry properties Field fieldWSRestUrl = DirectoryUtils.findFieldByTitleInTheList(CONSTANT_WS_REST_URL, getFields()); Field fieldBlobStore = DirectoryUtils.findFieldByTitleInTheList(CONSTANT_BLOBSTORE, getFields()); String strWSRestUrl = fieldWSRestUrl.getValue(); String strBlobStore = fieldBlobStore.getValue(); if (bTestDirectoryError && (StringUtils.isBlank(strWSRestUrl) || StringUtils.isBlank(strBlobStore))) { String strErrorMessage = I18nService.getLocalizedString(MESSAGE_ENTRY_NOT_WELL_CONFIGURED, locale); throw new DirectoryErrorException(this.getTitle(), strErrorMessage); } /** * 1) Get the files from the session * 2) Check if the user is uploading a file or not * 2A) If the user is uploading a file, the file should not be * stored in the blobstore yet * 2B) Otherwise, upload the file in blobstore : * 2B-1) Delete files from the blobstore * 2B-2) Upload files to the blostore */ /** 1) Get the files from the session */ List<FileItem> asynchronousFileItems = getFileSources(request); if ((asynchronousFileItems != null) && !asynchronousFileItems.isEmpty()) { /** 2) Check if the user is uploading a file or not */ String strUploadAction = DirectoryAsynchronousUploadHandler.getHandler().getUploadAction(request); if (StringUtils.isNotBlank(strUploadAction)) { /** * 2A) If the user is uploading a file, the file should not * be stored in the blobstore yet */ for (FileItem fileItem : asynchronousFileItems) { RecordField recordField = new RecordField(); recordField.setEntry(this); recordField.setFileName(fileItem.getName()); recordField.setFileExtension(fileItem.getContentType()); listRecordField.add(recordField); } } else { /** 2B) Otherwise, upload the file in blobstore : */ // Checks if (bTestDirectoryError) { this.checkRecordFieldData(asynchronousFileItems, locale); } /** 2B-1) Delete files from the blobstore */ try { handler.doRemoveFile(record, this, strWSRestUrl); } catch (BlobStoreClientException e) { AppLogService.debug(e); } /** 2B-2) Upload files to the blostore */ for (FileItem fileItem : asynchronousFileItems) { String strDownloadFileUrl = StringUtils.EMPTY; try { if (fileItem != null) { // Store the uploaded file in the blobstore webapp String strBlobKey = handler.doUploadFile(strWSRestUrl, fileItem, strBlobStore); strDownloadFileUrl = handler.getFileUrl(strWSRestUrl, strBlobStore, strBlobKey); } } catch (Exception e) { throw new DirectoryErrorException(this.getTitle(), e.getMessage()); } // Add record field RecordField recordField = new RecordField(); recordField.setEntry(this); recordField.setValue(strDownloadFileUrl); listRecordField.add(recordField); } } } else { // No uploaded files if (bTestDirectoryError && this.isMandatory()) { throw new DirectoryErrorException(this.getTitle()); } // Delete files from blobstore try { handler.doRemoveFile(record, this, strWSRestUrl); } catch (BlobStoreClientException e) { AppLogService.debug(e); } } } else { // Case if we get directly the url of the blob String[] listDownloadFileUrls = request.getParameterValues(Integer.toString(getIdEntry())); if ((listDownloadFileUrls != null) && (listDownloadFileUrls.length > 0)) { for (String strDownloadFileUrl : listDownloadFileUrls) { RecordField recordField = new RecordField(); recordField.setEntry(this); recordField.setValue( StringUtils.isNotBlank(strDownloadFileUrl) ? strDownloadFileUrl : StringUtils.EMPTY); listRecordField.add(recordField); } } } }
From source file:com.reachcall.pretty.http.ProxyServlet.java
@SuppressWarnings("unchecked") private void doMultipart(HttpPost method, HttpServletRequest req) throws ServletException, FileUploadException, UnsupportedEncodingException, IOException { DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize()); diskFileItemFactory.setRepository(TEMP_DIR); ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory); List<FileItem> fileItems = (List<FileItem>) upload.parseRequest(req); MultipartEntity entity = new MultipartEntity(); for (FileItem fItem : fileItems) { if (fItem.isFormField()) { LOG.log(Level.INFO, "Form field {0}", fItem.getName()); StringBody part = new StringBody(fItem.getFieldName()); entity.addPart(fItem.getFieldName(), part); } else {/* w w w . j a va2 s.co m*/ LOG.log(Level.INFO, "File item {0}", fItem.getName()); InputStreamBody file = new InputStreamBody(fItem.getInputStream(), fItem.getName(), fItem.getContentType()); entity.addPart(fItem.getFieldName(), file); } } method.setEntity(entity); }
From source file:com.square.composant.envoi.email.square.server.servlet.UploadFichierServlet.java
/** {@inheritDoc} */ @SuppressWarnings("unchecked") protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final boolean isMultipart = ServletFileUpload.isMultipartContent(request); // Cration d'un DiskFileItemFactory pour stocker les fichiers. if (isMultipart) { try {//from w w w . j a v a 2s . c om final FileItemFactory factory = new DiskFileItemFactory(); final ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding(ComposantEnvoiEmailConstants.ENCODAGE_UTF_8); // Rcupration des items contenus dans la requte final List<FileItem> listeItems = upload.parseRequest(request); // Parcours des items for (FileItem item : listeItems) { // Fichier uploader if (!item.isFormField()) { // Nom du fichier String nomFichier = ""; // on verifie si il y a un backslash if (item.getName().indexOf("\\") != -1) { // [\\\\] = expression rgulire pour dcouper suivant le backslash final String[] tabNomFichier = item.getName().split("\\\\"); nomFichier = tabNomFichier[tabNomFichier.length - 1]; } else { nomFichier = item.getName(); } // Type MIME final String typeMime = item.getContentType(); // Cration d'un fichier temporaire String prefixe = nomFichier; String suffixe = null; if (nomFichier.indexOf(".") != -1) { final int indexPoint = nomFichier.lastIndexOf("."); prefixe = nomFichier.substring(0, indexPoint); suffixe = nomFichier.substring(indexPoint); } if (prefixe.length() < 3) { response.getOutputStream() .print(ComposantEnvoiEmailConstants.ERREUR_UPLOAD_FICHIER_NOM_INCORRECT); } else { final File fichierTemporaire = File.createTempFile(prefixe, suffixe); item.write(fichierTemporaire); // Renvoi des infos concernant le fichier final StringBuffer infosFichier = new StringBuffer(); infosFichier.append(ComposantEnvoiEmailConstants.PARAM_NOM_FICHIER) .append(ComposantEnvoiEmailConstants.EGAL).append(nomFichier); infosFichier.append(ComposantEnvoiEmailConstants.ET); infosFichier.append(ComposantEnvoiEmailConstants.PARAM_PATH_FICHIER_TEMP) .append(ComposantEnvoiEmailConstants.EGAL) .append(fichierTemporaire.getCanonicalPath()); infosFichier.append(ComposantEnvoiEmailConstants.ET); infosFichier.append(ComposantEnvoiEmailConstants.PARAM_TYPE_MIME) .append(ComposantEnvoiEmailConstants.EGAL).append(typeMime); response.getOutputStream().print(URLEncoder.encode(infosFichier.toString(), ComposantEnvoiEmailConstants.ENCODAGE_UTF_8)); } } } } catch (FileUploadException e) { response.getOutputStream().print(ComposantEnvoiEmailConstants.ERREUR_UPLOAD_FICHIER); } catch (Exception e) { response.getOutputStream().print(ComposantEnvoiEmailConstants.ERREUR_UPLOAD_FICHIER); } } }
From source file:edu.purdue.pivot.skwiki.server.ImageUploaderServlet.java
@Override public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException { connection = null;//w w w .j a v a2 s .com Statement st = null; /* read database details from file */ BufferedReader br; current_project_name = ""; main_database_name = ""; try { br = new BufferedReader(new FileReader(this.getServletContext().getRealPath("/serverConfig.txt"))); StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { String first = line.substring(0, line.lastIndexOf(':')); String last = line.substring(line.lastIndexOf(':') + 1); if (first.contains("content_database")) { current_project_name = last; } if (first.contains("owner_database")) { main_database_name = last; } if (first.contains("username")) { postgres_name = last; } if (first.contains("password")) { postgres_password = last; } sb.append(line); sb.append(System.lineSeparator()); line = br.readLine(); } //String everything = sb.toString(); //System.out.println("file: "+everything); br.close(); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } finally { } try { connection = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5432/" + current_project_name, "postgres", "fujiko"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } String response = ""; int cont = 0; for (FileItem item : sessionFiles) { if (false == item.isFormField()) { cont++; try { String uuid = UUID.randomUUID().toString(); String saveName = uuid + '.' + FilenameUtils.getExtension(item.getName()); // String saveName = item.getName(); //write to database File file = new File(saveName); item.write(file); // / Save a list with the received files receivedFiles.put(item.getFieldName(), file); receivedContentTypes.put(item.getFieldName(), item.getContentType()); receivedFilePaths.put(item.getFieldName(), file.getAbsolutePath()); // / Send a customized message to the client. response += "File saved as " + file.getAbsolutePath(); //write filename to database String selectStr = "insert into images values (" + "\'" + item.getFieldName() + "\'," + "\'" + file.getAbsolutePath() + "\'" + ")"; st = connection.createStatement(); int textReturnCode = st.executeUpdate(selectStr); } catch (Exception e) { throw new UploadActionException(e.getMessage()); } } } // / Remove files from session because we have a copy of them removeSessionFileItems(request); // / Send your customized message to the client. return response; }
From source file:it.infn.ct.mpi_portlet.java
public void getInputForm(ActionRequest request) { if (PortletFileUpload.isMultipartContent(request)) try {/* w w w. ja v a 2 s . co m*/ FileItemFactory factory = new DiskFileItemFactory(); PortletFileUpload upload = new PortletFileUpload(factory); List items = upload.parseRequest(request); File repositoryPath = new File("/tmp"); DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setRepository(repositoryPath); Iterator iter = items.iterator(); String logstring = ""; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); logstring += LS + "field name: '" + fieldName + "' - '" + item.getString() + "'"; switch (inputControlsIds.valueOf(fieldName)) { case file_inputFile: inputFileName = item.getString(); processInputFile(item); break; case inputFile: inputFileText = item.getString(); break; case JobIdentifier: jobIdentifier = item.getString(); break; case cpunumber: cpunumber = item.getString(); break; default: _log.info("Unhandled input field: '" + fieldName + "' - '" + item.getString() + "'"); } // switch fieldName } // while iter.hasNext() _log.info(LS + "Reporting" + LS + "---------" + LS + logstring); } catch (Exception e) { _log.info("Caught exception while processing files to upload: '" + e.toString() + "'"); } // The input form do not use the "multipart/form-data" else { // Retrieve from the input form the given application values inputFileName = (String) request.getParameter("file_inputFile"); inputFileText = (String) request.getParameter("inputFile"); jobIdentifier = (String) request.getParameter("JobIdentifier"); cpunumber = (String) request.getParameter("cpunumber"); } // ! isMultipartContent // Show into the log the taken inputs _log.info(LS + "Taken input parameters:" + LS + "inputFileName: '" + inputFileName + "'" + LS + "inputFileText: '" + inputFileText + "'" + LS + "jobIdentifier: '" + jobIdentifier + "'" + LS + "cpunumber: '" + cpunumber + "'"); }
From source file:edu.emory.cci.aiw.cvrg.eureka.servlet.JobSubmitServlet.java
private Long submitJob(HttpServletRequest request, Principal principal) throws FileUploadException, IOException, ClientException, ParseException { DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); /*/* ww w . j a v a 2 s . c o m*/ *Set the size threshold, above which content will be stored on disk. */ fileItemFactory.setSizeThreshold(5 * 1024 * 1024); //5 MB /* * Set the temporary directory to store the uploaded files of size above threshold. */ fileItemFactory.setRepository(this.tmpDir); ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); /* * Parse the request */ List items = uploadHandler.parseRequest(request); Properties fields = new Properties(); for (Iterator itr = items.iterator(); itr.hasNext();) { FileItem item = (FileItem) itr.next(); /* * Handle Form Fields. */ if (item.isFormField()) { fields.setProperty(item.getFieldName(), item.getString()); } } JobSpec jobSpec = MAPPER.readValue(fields.getProperty("jobSpec"), JobSpec.class); for (Iterator itr = items.iterator(); itr.hasNext();) { FileItem item = (FileItem) itr.next(); if (!item.isFormField()) { //Handle Uploaded files. log("Spreadsheet upload for user " + principal.getName() + ": Field Name = " + item.getFieldName() + ", File Name = " + item.getName() + ", Content type = " + item.getContentType() + ", File Size = " + item.getSize()); if (item.getSize() > 0) { InputStream is = item.getInputStream(); try { this.servicesClient.upload(FilenameUtils.getName(item.getName()), jobSpec.getSourceConfigId(), item.getFieldName(), is); log("File '" + item.getName() + "' uploaded successfully"); } finally { if (is != null) { try { is.close(); } catch (IOException ignore) { } } } } else { log("File '" + item.getName() + "' ignored because it was zero length"); } } } URI uri = this.servicesClient.submitJob(jobSpec); String uriStr = uri.toString(); Long jobId = Long.valueOf(uriStr.substring(uriStr.lastIndexOf("/") + 1)); log("Job " + jobId + " submitted for user " + principal.getName()); return jobId; }
From source file:application.controllers.admin.EmotionList.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //upload image to browser for add emotions //upload image to browser for add emotions if (!ServletFileUpload.isMultipartContent(request)) { PrintWriter writer = response.getWriter(); writer.println("Request does not contain upload data"); writer.flush();/* w ww .ja v a2 s.c o m*/ return; } // configures upload settings DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(UploadConstant.THRESHOLD_SIZE); // Location to save data that is larger than maxMemSize. factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setFileSizeMax(UploadConstant.MAX_FILE_SIZE); upload.setSizeMax(UploadConstant.MAX_REQUEST_SIZE); // constructs the directory path to store upload file // String uploadPath = Registry.get("Host") +"/emotions-image/"+ UPLOAD_DIRECTORY; String uploadPath = Registry.get("imageHost") + "/emotions-image/" + UploadConstant.UPLOAD_DIRECTORY; // creates the directory if it does not exist File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdir(); } //list image user upload String[] arrLinkImage = null; try { int indexImage = 0; // parses the request's content to extract file data List formItems = upload.parseRequest(request); arrLinkImage = new String[formItems.size()]; Iterator iter = formItems.iterator(); // iterates over form's fields while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); // processes only fields that are not form fields if (!item.isFormField()) { String fileName = new File(item.getName()).getName(); String extensionImage = ""; for (int i = fileName.length() - 1; i >= 0; i--) { if (fileName.charAt(i) == '.') { break; } else { extensionImage = fileName.charAt(i) + extensionImage; } } String filePath = uploadPath + File.separator + fileName; File storeFile = new File(filePath); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); String fieldName = item.getFieldName(); // saves the file on disk item.write(storeFile); arrLinkImage[indexImage++] = item.getName(); } } } catch (Exception ex) { request.setAttribute("message", "There was an error: " + ex.getMessage()); } // request.setAttribute("arrLinkImage", arrLinkImage); // RequestDispatcher rd = request.getRequestDispatcher("/groupEmotion/emotion/add"); // rd.forward(request, response); // String sessionId = request.getAttribute("sessionIdAdmin").toString(); String sessionId = request.getSession().toString(); String groupId = request.getParameter("groupId"); Memcached.set("arrLinkImage-" + sessionId, 3600, arrLinkImage); response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); response.setHeader("Location", Registry.get("Host") + "/groupEmotion/emotion/add?groupId=" + groupId); response.setContentType("text/html"); }