List of usage examples for org.apache.commons.fileupload FileItem getContentType
String getContentType();
null
if not defined. From source file:mx.org.cedn.avisosconagua.engine.processors.Pronostico.java
/** * Processes an uploaded file and stores it in MongoDB. * @param item file item from the parsed servlet request * @param currentId ID for the current MongoDB object for the advice * @return file name/*from ww w .j a v a2 s . c o m*/ * @throws IOException */ private String processUploadedFile(FileItem item, String currentId) throws IOException { GridFS gridfs = MongoInterface.getInstance().getImagesFS(); GridFSInputFile gfsFile = gridfs.createFile(item.getInputStream()); String filename = currentId + ":" + item.getFieldName() + "_" + item.getName(); gfsFile.setFilename(filename); gfsFile.setContentType(item.getContentType()); gfsFile.save(); return filename; }
From source file:edu.lternet.pasta.portal.UploadEvaluateServlet.java
/** * Process the uploaded file//www. ja v a 2 s.c om * * @param item The multipart form file data. * * @return The uploaded file as File object. * * @throws Exception */ private File processUploadedFile(FileItem item) throws Exception { File eml = null; // Process a file upload if (!item.isFormField()) { // Get object information String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); String tmpdir = System.getProperty("java.io.tmpdir"); logger.debug("FILE: " + tmpdir + "/" + fileName); eml = new File(tmpdir + "/" + fileName); item.write(eml); } return eml; }
From source file:fr.paris.lutece.plugins.document.web.category.CategoryJspBean.java
/** * Modify Category/* w w w . j ava 2 s. c o m*/ * @param request The HTTP request * @return String The url page */ public String doModifyCategory(HttpServletRequest request) { Category category = null; String strCategoryName = request.getParameter(PARAMETER_CATEGORY_NAME).trim(); String strCategoryDescription = request.getParameter(PARAMETER_CATEGORY_DESCRIPTION).trim(); String strCategoryUpdateIcon = request.getParameter(PARAMETER_CATEGORY_UPDATE_ICON); String strWorkgroup = request.getParameter(PARAMETER_WORKGROUP_KEY); int nIdCategory = checkCategoryId(request); if (nIdCategory == ERROR_ID_CATEGORY) { return AdminMessageService.getMessageUrl(request, MESSAGE_CATEGORY_ERROR, AdminMessage.TYPE_ERROR); } // Mandatory field if ((strCategoryName.length() == 0) || (strCategoryDescription.length() == 0)) { return AdminMessageService.getMessageUrl(request, Messages.MANDATORY_FIELDS, AdminMessage.TYPE_STOP); } // check if category exist Collection<Category> categoriesList = CategoryHome.findByName(strCategoryName); if (!categoriesList.isEmpty() && (categoriesList.iterator().next().getId() != nIdCategory)) { return AdminMessageService.getMessageUrl(request, MESSAGE_CATEGORY_EXIST, AdminMessage.TYPE_STOP); } category = CategoryHome.find(nIdCategory); category.setName(strCategoryName); category.setDescription(strCategoryDescription); if (strCategoryUpdateIcon != null) { MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request; FileItem item = mRequest.getFile(PARAMETER_IMAGE_CONTENT); byte[] bytes = item.get(); category.setIconContent(bytes); category.setIconMimeType(item.getContentType()); } category.setWorkgroup(strWorkgroup); CategoryHome.update(category); return getHomeUrl(request); }
From source file:com.example.app.support.service.FileSaver.java
/** * Set the file on {@link E} and saves it. Returns the persisted instance of {@link E} * @param value the instance of {@link E} to set the file on and save * @param file the Image to save//from ww w . j a v a 2 s. c o m * @return the updated and persisted value */ public E save(@Nonnull E value, @Nullable FileItem file) { if (file == null) { value = _setFile.apply(value, null); } else { value = _saveValue.apply(value); FileEntity currFile = _getFile.apply(value); if (currFile == null) currFile = new FileEntity(); String fileName = StringFactory.getBasename(file.getName()); String ct = file.getContentType(); if (ct == null || "application/octet-stream".equals(ct)) ct = MimeTypeUtility.getInstance().getContentType(fileName); currFile.setContentType(ct); final DirectoryEntity directory = _getDirectory.apply(value, file); if (directory != null) { currFile.setName(_getFileName.apply(value, file)); FileSystemDAO.StoreRequest request = new FileSystemDAO.StoreRequest(directory, currFile, new FileItemByteSource(file)); request.setCreateMode(FileSystemEntityCreateMode.overwrite); currFile = _fileSystemDAO.store(request); } else { _logger.error("Unable to save File."); currFile = _getFile.apply(value); } value = _setFile.apply(value, currFile); } value = _saveValue.apply(value); return value; }
From source file:controllers.IndexController.java
@RequestMapping(value = "/upload", method = RequestMethod.POST) public ModelAndView uploadpic(HttpServletRequest request, ModelAndView model) { String path = request.getRealPath("/upload_images"); path = path.substring(0, path.indexOf("\\mavenproject1")); path = path + "\\mavenproject1\\mavenproject1\\src\\main\\webapp\\upload_images"; DiskFileItemFactory dfif = new DiskFileItemFactory(); ServletFileUpload uploader = new ServletFileUpload(dfif); try {// www .jav a2 s .c o m List<FileItem> fit = uploader.parseRequest(request); for (FileItem fileItem : fit) { try { contenttype = fileItem.getContentType(); contenttype = contenttype.substring(6, contenttype.length()); if (fileItem.isFormField() == false && contenttype.equals("jpeg") || contenttype.equals("png")) { file = new File(path + "/" + fileItem.getName()); fileItem.write(file); } } catch (Exception ey) { } } return model; } catch (Exception ex) { if (file.exists()) { file.delete(); } model.addObject("errorcode", ex.toString()); model.setViewName("nosuccessform"); return model; } }
From source file:com.picdrop.service.implementation.FileResourceService.java
protected FileType parseMimeType(FileItem file) throws ApplicationException, IOException { FileType mime = FileType.forName(file.getContentType()); if (mime.isUnknown()) { throw new ApplicationException().status(400) .devMessage(String.format("Invalid mime type detected '%s'", file.getContentType())) .code(ErrorMessageCode.BAD_UPLOAD_MIME); }/* ww w .j a v a2 s . c o m*/ Metadata mdata = new Metadata(); InputStream in = file.getInputStream(); String tikaMime = null; try { tikaMime = tika.detect(in, mdata); } finally { in.close(); } log.debug(SERVICE, "Mime types resolved. HTTP Header: '{}' Tika: '{}'", file.getContentType(), tikaMime); if (!FileType.forName(tikaMime).isCovering(mime)) { throw new ApplicationException().status(400).devMessage(String .format("Mime type mismatch, expected: '%s' detected: '%s'", file.getContentType(), tikaMime)) .code(ErrorMessageCode.BAD_UPLOAD_MIME); } return mime; }
From source file:Com.Dispatcher.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*from ww w . j av a 2 s. c o m*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { File file; Boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { return; } // Create a session object if it is already not created. HttpSession session = request.getSession(true); // Get session creation time. Date createTime = new Date(session.getCreationTime()); // Get last access time of this web page. Date lastAccessTime = new Date(session.getLastAccessedTime()); String visitCountKey = new String("visitCount"); String userIDKey = new String("userID"); String userID = new String("ABCD"); Integer visitCount = (Integer) session.getAttribute(visitCountKey); // Check if this is new comer on your web page. if (visitCount == null) { session.setAttribute(userIDKey, userID); } else { visitCount++; userID = (String) session.getAttribute(userIDKey); } session.setAttribute(visitCountKey, visitCount); 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(fileRepository)); // 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(); 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 to server in "/uploads/{sessionID}/" String clientDataPath = getServletContext().getInitParameter("clientFolder"); // TODO clear the client folder here // FileUtils.deleteDirectory(new File("clientDataPath")); if (fileName.lastIndexOf("\\") >= 0) { File input = new File(clientDataPath + session.getId() + "/input/"); input.mkdirs(); File output = new File(clientDataPath + session.getId() + "/output/"); output.mkdirs(); session.setAttribute("inputFolder", clientDataPath + session.getId() + "/input/"); session.setAttribute("outputFolder", clientDataPath + session.getId() + "/output/"); file = new File( input.getAbsolutePath() + "/" + fileName.substring(fileName.lastIndexOf("/"))); } else { File input = new File(clientDataPath + session.getId() + "/input/"); input.mkdirs(); File output = new File(clientDataPath + session.getId() + "/output/"); output.mkdirs(); session.setAttribute("inputFolder", clientDataPath + session.getId() + "/input/"); session.setAttribute("outputFolder", clientDataPath + session.getId() + "/output/"); file = new File( input.getAbsolutePath() + "/" + fileName.substring(fileName.lastIndexOf("/") + 1)); } fi.write(file); } } } catch (Exception ex) { System.out.println("Failure: File Upload"); System.out.println(ex); //TODO show error page for website } System.out.println("file uploaded"); // TODO make the fileRepository Folder generic so it doesnt need to be changed // for each migration of the program to a different server File input = new File((String) session.getAttribute("inputFolder")); File output = new File((String) session.getAttribute("outputFolder")); File profile = new File(getServletContext().getInitParameter("profileFolder")); File hintsXML = new File(getServletContext().getInitParameter("hintsXML")); System.out.println("folders created"); Controller controller = new Controller(input, output, profile, hintsXML); HashMap initialArtifacts = controller.initialArtifacts(); session.setAttribute("Controller", controller); System.out.println("Initialisation of profiles for session (" + session.getId() + ") is complete\n" + "Awaiting user to update parameters to generate next generation of results.\n"); String json = new Gson().toJson(initialArtifacts); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(json); }
From source file:fr.paris.lutece.plugins.suggest.business.EntryTypeImage.java
/** * save in the list of response the response associate to the entry in the form submit * @param nIdSuggestSubmit the id of the SuggestSubmit * @param request HttpRequest// www .j av a 2 s.c o m * @param listResponse the list of response associate to the entry in the form submit * @param locale the locale * @param plugin the plugin * @return a Form error object if there is an error in the response */ public FormError getResponseData(int nIdSuggestSubmit, HttpServletRequest request, List<Response> listResponse, Locale locale, Plugin plugin) { MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request; FileItem item = mRequest.getFile(SuggestUtils.EMPTY_STRING + this.getIdEntry()); byte[] bytes = item.get(); Response response = new Response(); response.setEntry(this); if (bytes != null) { ImageResource image = new ImageResource(); image.setImage(bytes); image.setMimeType(item.getContentType()); response.setImage(image); response.setValueResponse(FileUploadService.getFileNameOnly(item)); } else { if (this.isMandatory()) { FormError formError = new FormError(); formError.setMandatoryError(true); formError.setTitleQuestion(this.getTitle()); return formError; } } listResponse.add(response); return null; }
From source file:com.javaweb.controller.ThemTinTucServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request servlet request/*from w ww . ja va 2 s.c o m*/ * @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, ParseException { response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("UTF-8"); //response.setCharacterEncoding("UTF-8"); HttpSession session = request.getSession(); // session.removeAttribute("errorreg"); String TieuDe = "", NoiDung = "", ngaydang = "", GhiChu = "", fileName = ""; int idloaitin = 0, idTK = 0; TintucService tintucservice = new TintucService(); //File upload String folderupload = getServletContext().getInitParameter("file-upload"); String rootPath = getServletContext().getRealPath("/"); filePath = rootPath + folderupload; isMultipart = ServletFileUpload.isMultipartContent(request); response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); 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:\\Windows\\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(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); fileName = fi.getName(); String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); //change file name fileName = FileService.ChangeFileName(fileName); // 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)); } fi.write(file); // out.println("Uploaded Filename: " + fileName + "<br>"); } if (fi.isFormField()) { if (fi.getFieldName().equalsIgnoreCase("TieuDe")) { TieuDe = fi.getString("UTF-8"); } else if (fi.getFieldName().equalsIgnoreCase("NoiDung")) { NoiDung = fi.getString("UTF-8"); } else if (fi.getFieldName().equalsIgnoreCase("NgayDang")) { ngaydang = fi.getString("UTF-8"); } else if (fi.getFieldName().equalsIgnoreCase("GhiChu")) { GhiChu = fi.getString("UTF-8"); } else if (fi.getFieldName().equalsIgnoreCase("loaitin")) { idloaitin = Integer.parseInt(fi.getString("UTF-8")); } else if (fi.getFieldName().equalsIgnoreCase("idtaikhoan")) { idTK = Integer.parseInt(fi.getString("UTF-8")); } } } } catch (Exception ex) { System.out.println(ex); } Date NgayDang = new SimpleDateFormat("yyyy-MM-dd").parse(ngaydang); Tintuc tintuc = new Tintuc(idloaitin, idTK, fileName, TieuDe, NoiDung, NgayDang, GhiChu); boolean rs = tintucservice.InsertTintuc(tintuc); if (rs) { session.setAttribute("kiemtra", "1"); String url = "ThemTinTuc.jsp"; response.sendRedirect(url); } else { session.setAttribute("kiemtra", "0"); String url = "ThemTinTuc.jsp"; response.sendRedirect(url); } // try (PrintWriter out = response.getWriter()) { // /* TODO output your page here. You may use following sample code. */ // out.println("<!DOCTYPE html>"); // out.println("<html>"); // out.println("<head>"); // out.println("<title>Servlet ThemTinTucServlet</title>"); // out.println("</head>"); // out.println("<body>"); // out.println("<h1>Servlet ThemTinTucServlet at " + request.getContextPath() + "</h1>"); // out.println("</body>"); // out.println("</html>"); // } }
From source file:com.sun.socialsite.web.rest.servlets.UploadServlet.java
/** * Note: using SuppressWarnings annotation because the Commons FileUpload API is * not genericized./*w w w .jav a2s.c o m*/ */ @Override @SuppressWarnings(value = "unchecked") protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { // ensure calling app/gadget has perm to use SocialSite API SecurityToken token = new AuthInfo(req).getSecurityToken(); Factory.getSocialSite().getPermissionManager().checkPermission(requiredPerm, token); GroupManager gmgr = Factory.getSocialSite().getGroupManager(); ProfileManager pmgr = Factory.getSocialSite().getProfileManager(); int errorCode = -1; Group group = null; Profile profile = null; // parse URL to get route and subjectId String route = null; String subjectId = ""; if (req.getPathInfo() != null) { String[] pathInfo = req.getPathInfo().split("/"); route = pathInfo[1]; subjectId = pathInfo[2]; } // first, figure out destination profile or group and check the // caller's permission to upload an image for that profile or group if ("profile".equals(route)) { if (token.getViewerId().equals(subjectId)) { profile = pmgr.getProfileByUserId(subjectId); } else { errorCode = HttpServletResponse.SC_UNAUTHORIZED; } } else if ("group".equals(route)) { group = gmgr.getGroupByHandle(subjectId); if (group != null) { // ensure called is group ADMIN or founder Profile viewer = pmgr.getProfileByUserId(token.getViewerId()); GroupRelationship grel = gmgr.getMembership(group, viewer); if (grel == null || (grel.getRelcode() != GroupRelationship.Relationship.ADMIN && grel.getRelcode() != GroupRelationship.Relationship.FOUNDER)) { } else { errorCode = HttpServletResponse.SC_UNAUTHORIZED; } } else { // group not found errorCode = HttpServletResponse.SC_NOT_FOUND; } } // next, parse out the image and save it in profile or group if (errorCode != -1 && group == null && profile == null) { errorCode = HttpServletResponse.SC_NOT_FOUND; } else if (errorCode == -1) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); FileItem fileItem = null; List<FileItem> items = (List<FileItem>) upload.parseRequest(req); if (items.size() > 0) { fileItem = items.get(0); } if ((fileItem != null) && (types.contains(fileItem.getContentType()))) { // read incomining image via Commons Upload InputStream is = fileItem.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Utilities.copyInputToOutput(is, baos); byte[] byteArray = baos.toByteArray(); // save it in the profile or group indicated if (profile != null) { profile.setImageType(fileItem.getContentType()); profile.setImage(byteArray); pmgr.saveProfile(profile); Factory.getSocialSite().flush(); } else if (group != null) { group.setImageType(fileItem.getContentType()); group.setImage(byteArray); gmgr.saveGroup(group); Factory.getSocialSite().flush(); } else { // group or profile not indicated properly errorCode = HttpServletResponse.SC_NOT_FOUND; } } } if (errorCode == -1) { resp.sendError(HttpServletResponse.SC_OK); return; } else { resp.sendError(errorCode); } } catch (SecurityException sx) { log.error("Permission denied", sx); resp.sendError(HttpServletResponse.SC_UNAUTHORIZED); } catch (FileUploadException fx) { log.error("ERROR uploading profile image", fx); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } catch (SocialSiteException ex) { log.error("ERROR saving profile image", ex); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }