List of usage examples for org.apache.commons.fileupload.disk DiskFileItem getName
public String getName()
From source file:com.afspq.web.ProcessQuery.java
@SuppressWarnings({ "unused", "rawtypes" }) protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try {//from ww w .j a v a 2s . co m String root = getServletContext().getRealPath("/"); File path = new File(root + "/uploads"); List items = upload.parseRequest(request); if (!path.exists()) { boolean status = path.mkdirs(); } if (items.size() > 0) { DiskFileItem file = (DiskFileItem) items.get(0); File uploadedFile = new File(path + "/" + file.getName()); file.write(uploadedFile); request.setAttribute("results", new ImageResults().getResults(uploadedFile, imageSearch, 0, true)); request.getRequestDispatcher("imageResults.jsp").forward(request, response); } } catch (Exception e) { e.printStackTrace(); } } }
From source file:com.bruce.gogo.utils.JakartaMultiPartRequest.java
public String[] getFileNames(String fieldName) { List<FileItem> items = files.get(fieldName); if (items == null) { return null; }//www .j av a2 s .c o m List<String> fileNames = new ArrayList<String>(items.size()); for (int i = 0; i < items.size(); i++) { DiskFileItem fileItem = (DiskFileItem) items.get(i); fileNames.add(getCanonicalName(fileItem.getName())); } return (String[]) fileNames.toArray(new String[fileNames.size()]); }
From source file:com.ultrapower.eoms.common.plugin.ajaxupload.AjaxMultiPartRequest.java
public String[] getFileNames(String fieldName) { List<FileItem> items = files.get(fieldName); if (items == null) { return null; }//from w ww .j ava 2 s . c o m List<String> fileNames = new ArrayList<String>(items.size()); for (int i = 0; i < items.size(); i++) { DiskFileItem fileItem = (DiskFileItem) items.get(i); fileNames.add(getCanonicalName(fileItem.getName())); } return fileNames.toArray(new String[fileNames.size()]); }
From source file:com.liferay.portal.editor.fckeditor.receiver.impl.BaseCommandReceiver.java
public void fileUpload(CommandArgument commandArgument, HttpServletRequest request, HttpServletResponse response) {//from w w w . ja va 2 s. co m InputStream inputStream = null; String returnValue = null; try { ServletFileUpload servletFileUpload = new LiferayFileUpload( new LiferayFileItemFactory(UploadServletRequestImpl.getTempDir()), request); servletFileUpload .setFileSizeMax(PrefsPropsUtil.getLong(PropsKeys.UPLOAD_SERVLET_REQUEST_IMPL_MAX_SIZE)); LiferayServletRequest liferayServletRequest = new LiferayServletRequest(request); List<FileItem> fileItems = servletFileUpload.parseRequest(liferayServletRequest); Map<String, Object> fields = new HashMap<String, Object>(); for (FileItem fileItem : fileItems) { if (fileItem.isFormField()) { fields.put(fileItem.getFieldName(), fileItem.getString()); } else { fields.put(fileItem.getFieldName(), fileItem); } } DiskFileItem diskFileItem = (DiskFileItem) fields.get("NewFile"); String fileName = StringUtil.replace(diskFileItem.getName(), CharPool.BACK_SLASH, CharPool.SLASH); String[] fileNameArray = StringUtil.split(fileName, '/'); fileName = fileNameArray[fileNameArray.length - 1]; String contentType = diskFileItem.getContentType(); if (Validator.isNull(contentType) || contentType.equals(ContentTypes.APPLICATION_OCTET_STREAM)) { contentType = MimeTypesUtil.getContentType(diskFileItem.getStoreLocation()); } if (diskFileItem.isInMemory()) { inputStream = diskFileItem.getInputStream(); } else { inputStream = new ByteArrayFileInputStream(diskFileItem.getStoreLocation(), LiferayFileItem.THRESHOLD_SIZE); } long size = diskFileItem.getSize(); returnValue = fileUpload(commandArgument, fileName, inputStream, contentType, size); } catch (Exception e) { FCKException fcke = null; if (e instanceof FCKException) { fcke = (FCKException) e; } else { fcke = new FCKException(e); } Throwable cause = fcke.getCause(); returnValue = "203"; if (cause != null) { String causeString = GetterUtil.getString(cause.toString()); if (causeString.contains("NoSuchFolderException") || causeString.contains("NoSuchGroupException")) { returnValue = "204"; } else if (causeString.contains("ImageNameException")) { returnValue = "205"; } else if (causeString.contains("FileExtensionException") || causeString.contains("FileNameException")) { returnValue = "206"; } else if (causeString.contains("PrincipalException")) { returnValue = "207"; } else if (causeString.contains("ImageSizeException") || causeString.contains("FileSizeException")) { returnValue = "208"; } else if (causeString.contains("SystemException")) { returnValue = "209"; } else { throw fcke; } } _writeUploadResponse(returnValue, response); } finally { StreamUtil.cleanUp(inputStream); } _writeUploadResponse(returnValue, response); }
From source file:fr.ippon.wip.http.request.MultipartRequestBuilder.java
public HttpRequestBase buildHttpRequest() throws URISyntaxException { MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); try {/*www.j a v a2 s. c om*/ for (DiskFileItem fileItem : files) { if (fileItem.isFormField()) multipartEntity.addPart(fileItem.getFieldName(), new StringBody(new String(fileItem.get()))); else { // FileBody fileBody = new FileBody(fileItem.getStoreLocation(), fileItem.getName(), fileItem.getContentType(), fileItem.getCharSet()); InputStreamBody fileBody = new InputStreamKnownSizeBody(fileItem.getInputStream(), fileItem.get().length, fileItem.getContentType(), fileItem.getName()); multipartEntity.addPart(fileItem.getFieldName(), fileBody); } } // some request may have additional parameters in a query string if (parameterMap != null) for (Entry<String, String> entry : parameterMap.entries()) multipartEntity.addPart(entry.getKey(), new StringBody(entry.getValue())); } catch (Exception e) { e.printStackTrace(); } HttpPost postRequest = new HttpPost(requestedURL); postRequest.setEntity(multipartEntity); return postRequest; }
From source file:fr.ippon.wip.portlet.WIPConfigurationPortlet.java
/** * Process the user action: a configuration can be deleted, selected or * saved.//from w ww .j av a2 s . c om */ @Override public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException { PortletSession session = request.getPortletSession(); if (fileUploadPortlet.isMultipartContent(request)) { try { List<DiskFileItem> fileItems = fileUploadPortlet.parseRequest(request); for (DiskFileItem fileItem : fileItems) { // TODO : ??? String newName = FilenameUtils.concat(deployPath, fileItem.getName()); File file = fileItem.getStoreLocation(); file.renameTo(new File(newName)); } request.setAttribute(Attributes.PAGE.name(), Pages.EXISTING_CONFIG.name()); } catch (FileUploadException e) { e.printStackTrace(); } return; } String page = request.getParameter(Attributes.PAGE.name()); if (!StringUtils.isEmpty(page)) { session.setAttribute(Attributes.PAGE.name(), Pages.valueOf(page)); return; } String configName = request.getParameter(Attributes.ACTION_SELECT_CONFIGURATION.name()); if (!StringUtils.isEmpty(configName) && configurationDAO.exists(configName)) { session.setAttribute(Attributes.CONFIGURATION_NAME.name(), configName); session.setAttribute(Attributes.PAGE.name(), Pages.GENERAL_SETTINGS); return; } configName = request.getParameter(Attributes.ACTION_DELETE_CONFIGURATION.name()); if (!StringUtils.isEmpty(configName)) { if (WIPUtil.getConfiguration(request).getName().equals(configName)) session.setAttribute(Attributes.CONFIGURATION_NAME.name(), AbstractConfigurationDAO.DEFAULT_CONFIG_NAME); configurationDAO.delete(configurationDAO.read(configName)); return; } configName = request.getParameter(Attributes.ACTION_SAVE_CONFIGURATION_AS.name()); if (!StringUtils.isEmpty(configName)) { WIPConfiguration configuration = WIPUtil.getConfiguration(request); WIPConfiguration newConfiguration = (WIPConfiguration) configuration.clone(); newConfiguration.setName(configName); newConfiguration = configurationDAO.create(newConfiguration); session.setAttribute(Attributes.CONFIGURATION_NAME.name(), newConfiguration.getName()); session.setAttribute(Attributes.PAGE.name(), Pages.GENERAL_SETTINGS); return; } if (request.getParameter("form") != null) { switch (Integer.valueOf(request.getParameter("form"))) { case 1: handleGeneralSettings(request, response); break; case 2: handleClipping(request, response); break; case 3: handleHtmlRewriting(request, response); break; case 4: handleCSSRewriting(request, response); break; case 5: handleJSRewriting(request, response); break; case 6: handleCaching(request, response); break; case 7: handleLTPAAuthentication(request, response); break; } } }
From source file:com.novartis.opensource.yada.Service.java
/** * Obtains list of {@link FileItem} from {@link YADARequest#getUploadItems()}, extracts item metadata and wraps it in json * @return a json string containing pertinent metadata about the upload, including where to get it from the file system * @throws YADAPluginException when plugin execution fails * @throws YADAExecutionException when the upload result configuration fails * @see YADARequest#getUploadItems()/*w ww.ja va 2 s. c o m*/ */ private String executeUpload() throws YADAPluginException, YADAExecutionException { //TODO move upload item processing to this method from YADARequest String result = engageBypass(this.getYADARequest()); l.debug("Select bypass [result] is [" + result + "]"); if (result != null) { return result; } engagePreprocess(getYADARequest()); try { /* must return a json object like: * {"files": [ { "name": "picture1.jpg", "size": 902604, "url": "http:\/\/example.org\/files\/picture1.jpg", "thumbnailUrl": "http:\/\/example.org\/files\/thumbnail\/picture1.jpg", "deleteUrl": "http:\/\/example.org\/files\/picture1.jpg", "deleteType": "DELETE" }, { "name": "picture2.jpg", "size": 841946, "url": "http:\/\/example.org\/files\/picture2.jpg", "thumbnailUrl": "http:\/\/example.org\/files\/thumbnail\/picture2.jpg", "deleteUrl": "http:\/\/example.org\/files\/picture2.jpg", "deleteType": "DELETE" } ]} */ JSONArray files = new JSONArray(); for (FileItem fItem : getYADARequest().getUploadItems()) { JSONObject f = new JSONObject(); if (fItem.isFormField()) { f.put("formField", true); f.put("name", fItem.getFieldName()); f.put("value", fItem.getString()); } else { DiskFileItem item = (DiskFileItem) fItem; l.debug(item.toString()); f.put("name", item.getName()); f.put("size", item.getSize()); f.put("path", item.getStoreLocation().getAbsolutePath()); f.put("url", ""); f.put("thumbnailUrl", ""); f.put("deleteUrl", ""); f.put("deleteType", ""); } files.put(f); } result = new JSONObject().put("files", files).toString(); } catch (JSONException e) { l.error(e.getMessage()); e.printStackTrace(); throw new YADAExecutionException(e.getMessage()); } result = engagePostprocess(result); l.debug("result:" + result); return result; }
From source file:cServ.AltaDoc.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from ww w. j a va 2s . co m * * @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 { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { System.out.println("hit altadoc"); //begin database operation String nomArch = ""; String nombre = ""; String contra = ""; int id = 0; System.out.println(request.getParameter("idprofe")); String displayString = "Contrasea incorrecta"; String divColor = "danger"; String rdrUrl = "<meta http-equiv=\"refresh\" content=\"2;url=pages/profesor/adminDocs.jsp\" >"; //start file up FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List items = null; try { items = upload.parseRequest(request); } catch (Exception e) { e.printStackTrace(); } for (Iterator it = items.iterator(); it.hasNext();) { DiskFileItem diskFileItem = (DiskFileItem) it.next(); if (diskFileItem.isFormField()) { String fieldname = diskFileItem.getFieldName(); String fieldvalue = diskFileItem.getString(); System.out.println("fn: " + fieldname + " fv " + fieldvalue); if (fieldname.equals("nombre")) { nombre = fieldvalue; } else if (fieldname.equals("contra")) { contra = fieldvalue; } else if (fieldname.equals("idprofe")) { id = Integer.parseInt(fieldvalue); } } else { //start getpath String relativeWebPath = "/../../web/pages/profesor/adminDocsPanels/docDump/"; System.out.println("relative thing " + getServletContext().getRealPath(relativeWebPath)); System.out.println(relativeWebPath); String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath); System.out.println("complete path " + absoluteDiskPath + "\\" + nomArch); absoluteDiskPath += "\\" + nomArch; //end getpath byte[] fileBytes = diskFileItem.get(); nomArch = diskFileItem.getName(); File file = new File(absoluteDiskPath + diskFileItem.getName()); FileOutputStream fileOutputStream = new FileOutputStream(file); fileOutputStream.write(fileBytes); fileOutputStream.flush(); } } //end file up //start db insertion Validator valid = new Validator(); valid.ValidatePDF(nomArch); if (valid.isValid() == true) { String adString = altaDoc(id, nomArch); if (adString.equals("operacion realizada")) { displayString = "Documento dado de alta"; divColor = "success"; rdrUrl = "<meta http-equiv=\"refresh\" content=\"2;url=pages/profesor/adminDocs.jsp\" >"; } } else { displayString = "Archivo no vlido"; divColor = "danger"; rdrUrl = "<meta http-equiv=\"refresh\" content=\"2;url=pages/profesor/adminDocs.jsp\" >"; } //end db insertion out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<link rel=\"stylesheet\" href=\"css/style.css\">"); out.println("<title>Servlet AltaGrupo</title>"); out.println("</head>"); out.println("<body>"); out.println("<div class=\"container\">\n" + " <div class=\"row\">\n" + " <br><br>\n" + " <div class=\"panel panel-" + divColor + "\">\n" + " <div class=\"panel-heading\">\n" + " <h3 class=\"panel-title\">Espera</h3>\n" + " </div>\n" + " <div class=\"panel-body\">\n" + " " + displayString + " \n" + " </div>\n" + " </div>\n" + " </div>\n" + " </div>"); out.println(rdrUrl); out.println("</body>"); out.println("</html>"); //end database operation } catch (Exception ex) { ex.printStackTrace(); } }
From source file:com.novartis.opensource.yada.YADARequest.java
/** * Sets the upload items which will then be dervied from the * YADARequest by the preprocessor plugin * /*from ww w .j a v a 2s . c om*/ * @param uploadItems list of form field name/value pairs and upload content * @throws YADARequestException when a method invocation problem occurs while setting parameter values */ public void setUploadItems(List<FileItem> uploadItems) throws YADARequestException { this.uploadItems = uploadItems; Iterator<FileItem> iter = uploadItems.iterator(); while (iter.hasNext()) { DiskFileItem fi = (DiskFileItem) iter.next(); l.debug(fi); // set parameters from form fields if (fi.isFormField()) { String field = fi.getFieldName(); String value = fi.getString(); l.debug("field is [" + field + "], value is [" + value + "]"); invokeSetter(field, new String[] { value }); addToMap(field, new String[] { value }); } else { File f; String fPath; String fName; try { // execute plugin, as we are not calling a WS f = fi.getStoreLocation(); // tmp dir fPath = f.getAbsolutePath(); // uploaded file fName = fi.getName(); // original file name } finally { f = null; } addArg(fPath); addArg(fName); } } l.debug(getFormattedDebugString("uploadItems", uploadItems.toString())); }
From source file:org.datacleaner.monitor.server.media.FileUploadServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { clearSession(req);/* ww w .j a va 2s .c o m*/ File tempFolder = FileHelper.getTempDir(); try { File subDirectory = new File(tempFolder, ".datacleaner_upload"); if (subDirectory.mkdirs()) { tempFolder = subDirectory; } } catch (Exception e) { logger.warn("Could not create subdirectory in temp folder", e); } final FileItemFactory fileItemFactory = new DiskFileItemFactory(0, tempFolder); final ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory); servletFileUpload.setFileSizeMax(FILE_SIZE_MAX); servletFileUpload.setSizeMax(REQUEST_SIZE_MAX); final List<Object> resultFileElements = new ArrayList<Object>(); final HttpSession session = req.getSession(); try { int index = 0; @SuppressWarnings("unchecked") final List<DiskFileItem> items = servletFileUpload.parseRequest(req); for (DiskFileItem item : items) { if (item.isFormField()) { logger.warn("Ignoring form field in request: {}", item); } else { final String sessionKey = "file_upload_" + index; final File file = item.getStoreLocation(); String filename = toFilename(item.getName()); logger.info("File '{}' uploaded to temporary location: {}", filename, file); session.setAttribute(sessionKey, file); final Map<String, String> resultItem = new LinkedHashMap<String, String>(); resultItem.put("field_name", item.getFieldName()); resultItem.put("file_name", filename); resultItem.put("content_type", item.getContentType()); resultItem.put("size", Long.toString(item.getSize())); resultItem.put("session_key", sessionKey); resultFileElements.add(resultItem); index++; } } } catch (FileUploadException e) { logger.error("Unexpected file upload exception: " + e.getMessage(), e); throw new IOException(e); } final String contentType = req.getParameter("contentType"); if (contentType == null) { resp.setContentType("application/json"); } else { resp.setContentType(contentType); } final Map<String, Object> resultMap = new LinkedHashMap<String, Object>(); resultMap.put("status", "success"); resultMap.put("files", resultFileElements); // write result as JSON final ObjectMapper objectMapper = new ObjectMapper(); objectMapper.writeValue(resp.getOutputStream(), resultMap); }