List of usage examples for org.apache.commons.fileupload FileItem getFieldName
String getFieldName();
From source file:com.insurance.manage.UploadFile.java
private void uploadFire(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // boolean isMultipart = ServletFileUpload.isMultipartContent(request); // Create a factory for disk-based file items String custId = null;/*from w w w . j ava 2 s . co m*/ String year = null; String license = null; CustomerManager cManage = new CustomerManager(); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1 * 1024 * 1024); //1 MB factory.setRepository(new File("temp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); HttpSession session = request.getSession(); // Parse the request // System.out.println("--------- Uploading --------------"); try { List /* FileItem */ items = upload.parseRequest(request); // Process the uploaded items Iterator iter = items.iterator(); File fi = null; File file = null; // Calendar calendar = Calendar.getInstance(); // DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); // String fileName = df.format(calendar.getTime()) + ".jpg"; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { // System.out.println(item.getFieldName()+" : "+item.getName()+" : "+item.getString()+" : "+item.getContentType()); if (item.getFieldName().equals("custId") && !item.getString().equals("")) { custId = item.getString(); System.out.println("custId : " + custId); } if (item.getFieldName().equals("year") && !item.getString().equals("")) { year = item.getString(); System.out.println("year : " + year); } } else { // Handle Uploaded files. // System.out.println("Handle Uploaded files."); String fileName = year + custId + ".jpg"; if (item.getFieldName().equals("fire") && !item.getName().equals("")) { fi = new File(item.getName()); File uploadedFile = new File(getServletContext().getRealPath("/images/fire/" + fileName)); item.write(uploadedFile); cManage.updatePicture(custId, year, license, "firepic", fileName); } } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } request.setAttribute("url", "setup/CustomerMultiMT.jsp?action=search&custId=" + custId); request.setAttribute("msg", "!!!Uploading !!!"); getServletConfig().getServletContext().getRequestDispatcher("/Reload.jsp").forward(request, response); }
From source file:com.insurance.manage.UploadFile.java
private void uploadLife(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // boolean isMultipart = ServletFileUpload.isMultipartContent(request); // Create a factory for disk-based file items String custId = null;/*from w w w. j av a 2s . c o m*/ String year = null; String license = null; CustomerManager cManage = new CustomerManager(); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1 * 1024 * 1024); //1 MB factory.setRepository(new File("temp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); HttpSession session = request.getSession(); // Parse the request // System.out.println("--------- Uploading --------------"); try { List /* FileItem */ items = upload.parseRequest(request); // Process the uploaded items Iterator iter = items.iterator(); File fi = null; File file = null; // Calendar calendar = Calendar.getInstance(); // DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); // String fileName = df.format(calendar.getTime()) + ".jpg"; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { // System.out.println(item.getFieldName()+" : "+item.getName()+" : "+item.getString()+" : "+item.getContentType()); if (item.getFieldName().equals("custId") && !item.getString().equals("")) { custId = item.getString(); System.out.println("custId : " + custId); } if (item.getFieldName().equals("year") && !item.getString().equals("")) { year = item.getString(); System.out.println("year : " + year); } } else { // Handle Uploaded files. // System.out.println("Handle Uploaded files."); String fileName = year + custId + ".jpg"; if (item.getFieldName().equals("life") && !item.getName().equals("")) { fi = new File(item.getName()); File uploadedFile = new File(getServletContext().getRealPath("/images/life/" + fileName)); item.write(uploadedFile); cManage.updatePicture(custId, year, license, "lifepic", fileName); } } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } request.setAttribute("url", "setup/CustomerMultiMT.jsp?action=search&custId=" + custId); request.setAttribute("msg", "!!!Uploading !!!"); getServletConfig().getServletContext().getRequestDispatcher("/Reload.jsp").forward(request, response); }
From source file:ambit2.rest.task.CallableFileImport.java
public CallableFileImport(ClientInfo client, SourceDataset dataset, List<FileItem> items, String fileUploadField, Connection connection, DatasetURIReporter<IQueryRetrieval<ISourceDataset>, ISourceDataset> reporter, ConformerURIReporter compoundReporter, boolean firstCompoundOnly, USERID token) { this(client, dataset, (File) null, connection, reporter, compoundReporter, firstCompoundOnly, token); for (final Iterator<FileItem> it = items.iterator(); it.hasNext();) { FileItem fi = it.next(); if (!fi.isFormField()) continue; if (fi.getFieldName().equals("match")) { try { setMatcher(IStructureKey.Matcher.valueOf(fi.getString()).getMatcher()); break; } catch (Exception x) { setMatcher(null);//from w ww .j a v a 2 s . c o m } } } upload = new CallableFileUpload(items, new String[] { fileUploadField }) { @Override public Reference createReference() { return null; } @Override protected void processFile(String fieldname, File file, String description) throws Exception { setFile(file, description); } @Override protected void processProperties(Hashtable<String, String> properties) throws Exception { setProperties(properties); } }; }
From source file:edu.wustl.bulkoperator.action.BulkHandler.java
/** * This method will be called to get request parameters. * @param request HttpServletRequest.// w w w. ja v a 2s.com * @param bulkOperationForm form. * @throws BulkOperationException Exception. */ private void getRequestParameters(HttpServletRequest request, BulkOperationForm bulkOperationForm) throws BulkOperationException { try { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(new File(CommonServiceLocator.getInstance().getAppHome())); ServletFileUpload servletFileUpload = new ServletFileUpload(factory); // If file size exceeds, a FileUploadException will be thrown servletFileUpload.setSizeMax(10000 * 1000 * 100 * 10); List<FileItem> fileItems; fileItems = servletFileUpload.parseRequest(request); Iterator<FileItem> itr = fileItems.iterator(); while (itr.hasNext()) { FileItem fileItem = itr.next(); //Check if not form field so as to only handle the file inputs //else condition handles the submit button input if (!fileItem.isFormField()) { if ("csvFile".equals(fileItem.getFieldName())) { bulkOperationForm.setCsvFile(getFormFile(fileItem)); } else { bulkOperationForm.setXmlTemplateFile(getFormFile(fileItem)); } logger.info("Field =" + fileItem.getFieldName()); } else { if ("operation".equals(fileItem.getFieldName())) { bulkOperationForm.setOperationName(fileItem.getString()); } } } } catch (Exception exp) { ErrorKey errorkey = ErrorKey.getErrorKey("bulk.operation.request.param.error"); throw new BulkOperationException(errorkey, exp, exp.getMessage()); } }
From source file:importer.handler.post.ImporterPostHandler.java
/** * Parse the import params from the request * @param request the http request/*from w w w.ja v a2 s. co m*/ */ void parseImportParams(HttpServletRequest request) throws AeseException { try { FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List items = upload.parseRequest(request); for (int i = 0; i < items.size(); i++) { FileItem item = (FileItem) items.get(i); if (item.isFormField()) { String fieldName = item.getFieldName(); if (fieldName != null) { String contents = item.getString(); if (fieldName.equals(Params.DOCID)) { if (contents.startsWith("/")) { contents = contents.substring(1); int pos = contents.indexOf("/"); if (pos != -1) { database = contents.substring(0, pos); contents = contents.substring(pos + 1); } } docid = contents; } else if (fieldName.startsWith(Params.SHORT_VERSION)) nameMap.put(fieldName.substring(Params.SHORT_VERSION.length()), item.getString()); else if (fieldName.equals(Params.LC_STYLE) || fieldName.equals(Params.STYLE) || fieldName.equals(Params.CORFORM)) { jsonKeys.put(fieldName.toLowerCase(), contents); style = contents; } else if (fieldName.equals(Params.DEMO)) { if (contents != null && contents.equals("brillig")) demo = false; else demo = true; } else if (fieldName.equals(Params.TITLE)) title = contents; else if (fieldName.equals(Params.FILTER)) filterName = contents.toLowerCase(); else if (fieldName.equals(Params.SIMILARITY)) similarityTest = contents != null && contents.equals("1"); else if (fieldName.equals(Params.SPLITTER)) splitterName = contents; else if (fieldName.equals(Params.STRIPPER)) stripperName = contents; else if (fieldName.equals(Params.TEXT)) textName = contents.toLowerCase(); else if (fieldName.equals(Params.DICT)) dict = contents; else if (fieldName.equals(Params.ENCODING)) encoding = contents; else if (fieldName.equals(Params.HH_EXCEPTIONS)) hhExceptions = contents; else jsonKeys.put(fieldName, contents); } } else if (item.getName().length() > 0) { try { // assuming that the contents are text //item.getName retrieves the ORIGINAL file name String type = item.getContentType(); if (type != null && type.startsWith("image/")) { InputStream is = item.getInputStream(); ByteHolder bh = new ByteHolder(); while (is.available() > 0) { byte[] b = new byte[is.available()]; is.read(b); bh.append(b); } ImageFile iFile = new ImageFile(item.getName(), item.getContentType(), bh.getData()); images.add(iFile); } else { byte[] rawData = item.get(); guessEncoding(rawData); //System.out.println(encoding); File f = new File(item.getName(), new String(rawData, encoding)); files.add(f); } } catch (Exception e) { throw new AeseException(e); } } } if (style == null) style = DEFAULT_STYLE; } catch (Exception e) { throw new AeseException(e); } }
From source file:com.look.UploadPostServlet.java
/*************************************************************************** * Processes request data and saves into instance variables * @param request HttpServletRequest from client * @return True if successfully handled, false otherwise *//*w w w . j a v a2s . c o m*/ private boolean handleRequest(HttpServletRequest request) { if (ServletFileUpload.isMultipartContent(request)) { try { List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); boolean success = true; for (FileItem item : multiparts) { if (!item.isFormField()) { // Process form file field (input type="file"). String fieldName = item.getFieldName(); String filename = item.getName(); if (filename.equals("")) { //only update responseMessage if there isn't one yet if (responseMessage.equals("")) { responseMessage = "Please choose an image"; } success = false; } String clientFileName = FilenameUtils.getName("TEMP_" + item.getName().replaceAll(" ", "")); imageExtension = FilenameUtils.getExtension(clientFileName); imageURL = clientFileName + "." + imageExtension; fileContent = item.getInputStream(); } else { String fieldName = item.getFieldName(); String value = item.getString(); //only title is required if (value.equals("") && (fieldName.equals("title"))) { responseMessage = "Please enter a title"; success = false; } switch (fieldName) { case TITLE_FIELD_NAME: title = value; break; case DESCRIPTION_FIELD_NAME: description = value; break; case TAGS_FIELD_NAME: tags = value; if (!tags.equals("")) { tagList = new LinkedList<>(Arrays.asList(tags.split(" "))); for (int i = 0; i < tagList.size(); i++) { String tag = tagList.get(i); if (tag.charAt(0) != '#') { if (responseMessage.equals("")) { responseMessage = "Tags must begin with #"; success = false; } tagList.remove(i); } else if (!StringUtils.isAlphanumeric(tag.substring(1))) { log.info(tag.substring(1)); if (responseMessage.equals("")) { responseMessage = "Tags must only contain numbers and letters"; success = false; } tagList.remove(i); } else if (tag.length() > 20) { if (responseMessage.equals("")) { responseMessage = "Tags must be 20 characters or less"; success = false; } tagList.remove(i); } else { //tag is valid, remove the '#' for storage tagList.set(i, tag.substring(1)); } } } //now have list of alphanumeric tags of 20 chars or less break; } } } if (!success) { return false; } } catch (FileUploadException | IOException ex) { Logger.getLogger(UploadPostServlet.class.getName()).log(Level.SEVERE, null, ex); return false; } } else { request.setAttribute("message", "File upload request not found"); return false; } return true; }
From source file:net.ion.radon.impl.let.webdav.FCKConnectorRestlet.java
protected void handlePost(final Request request, final Response response, final String currentFolderStr) { final Form parameters = request.getResourceRef().getQueryAsForm(); final String commandStr = parameters.getValues("Command"); String retVal = "0"; String newName = ""; if (!commandStr.equalsIgnoreCase("FileUpload")) retVal = "203"; else {/* www . j a va 2 s.c om*/ final RestletFileUpload upload = new RestletFileUpload(new DiskFileItemFactory()); try { final List<?> items = upload.parseRequest(request); final Map<String, Object> fields = new HashMap<String, Object>(); final Iterator<?> iterator = items.iterator(); while (iterator.hasNext()) { final FileItem item = (FileItem) iterator.next(); if (item.isFormField()) fields.put(item.getFieldName(), item.getString()); else fields.put(item.getFieldName(), item); } final FileItem uploadFile = (FileItem) fields.get("NewFile"); String fileNameLong = uploadFile.getName(); fileNameLong = fileNameLong.replace('\\', '/'); final String[] pathParts = fileNameLong.split("/"); final String fileName = pathParts[pathParts.length - 1]; final String nameWithoutExt = getNameWithoutExtension(fileName); final String ext = getExtension(fileName); File pathToSave = new File(currentFolderStr, fileName); int counter = 1; while (pathToSave.exists()) { newName = nameWithoutExt + "(" + (counter++) + ")" + "." + ext; retVal = "201"; pathToSave = new File(currentFolderStr, newName); } try { OutputStream fout = vfs.getOutputStream(VFSUtils.parseVFSPath(pathToSave.getPath())); fout.write(uploadFile.get()); fout.close(); } catch (Exception e) { } // uploadFile.write(pathToSave); } catch (final Exception e) { e.printStackTrace(); retVal = "203"; } } response.setStatus(Status.SUCCESS_OK); Form headers = (Form) response.getAttributes().get("org.restlet.http.headers"); if (headers == null) { headers = new Form(); response.getAttributes().put("org.restlet.http.headers", headers); } headers.add("Content-type", "text/xml; charset=UTF-8"); headers.add("Cache-control", "no-cache"); String script = "<html><head><title></title><script type=\"text/javascript\">"; script += "function doWork() {"; script += "window.parent.frames['frmUpload'].OnUploadCompleted(" + retVal + ",'" + newName + "');"; // script += "window.parent.OnUploadComplete(" + retVal + ",'" + newName + "', '" + newName + "');"; // script += "window.location.reload(true);"; script += "}</script></head><body onload=\"doWork()\">Upload done!</body></html>"; response.setEntity(new StringRepresentation(script, MediaType.TEXT_HTML)); // System.out.println(script); }
From source file:Control.HandleAddRestaurant.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//www.j av a 2 s. 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, FileUploadException, Exception { response.setContentType("text/html;charset=UTF-8"); HttpSession session = request.getSession(); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ String path = getClass().getResource("/").getPath(); String[] tempS = null; if (Paths.path == null) { File file = new File(path + "test.html"); path = file.getParent(); File file1 = new File(path + "test1.html"); path = file1.getParent(); File file2 = new File(path + "test1.html"); path = file2.getParent(); Paths.path = path; } else { path = Paths.path; } path = Paths.tempPath; Restaurant temp = new Restaurant(); String name = null; String sepName = Tools.CurrentTime(); if (ServletFileUpload.isMultipartContent(request)) { List<?> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); Iterator iter = multiparts.iterator(); int index = 0; tempS = new String[multiparts.size() - 1]; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { name = new File(item.getName()).getName(); String FilePath = path + Paths.logoPathStore + sepName + name; item.write(new File(FilePath)); } else { String test = item.getFieldName(); tempS[index++] = item.getString(); } } index = 0; temp.ID = tempS[index++]; temp.name = tempS[index++]; temp.address = tempS[index++]; temp.city = tempS[index++]; temp.state = tempS[index++]; temp.zipcode = tempS[index++]; temp.email = tempS[index++]; temp.phone = tempS[index++]; temp.monHours = tempS[index++]; temp.sunHours = tempS[index++]; temp.minPrice = Double.parseDouble(tempS[index++]); temp.fee = Double.parseDouble(tempS[index++]); temp.type = Integer.parseInt(tempS[index++]); temp.logoImage = Paths.logoPath + sepName + name; } if (Restaurant.checkExisted(temp.ID, temp.name)) { response.sendRedirect("./Admin/AddRestaurant.jsp?index=1"); } else { if (Restaurant.addNewRestaurant(temp)) { Tools.updateRestaurants(session); response.sendRedirect("./Admin/AddRestaurant.jsp?index=2"); } else { response.sendRedirect("./Admin/AddRestaurant.jsp?index=3"); } } } catch (Exception e) { response.sendRedirect("./Admin/AddRestaurant.jsp?index=0"); } }
From source file:com.cognitivabrasil.repositorio.web.FileController.java
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST) @ResponseBody//from w ww. j av a2 s. c o m public String upload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, org.apache.commons.fileupload.FileUploadException { if (file == null) { file = new Files(); file.setSizeInBytes(0L); } Integer docId = null; String docPath = null; String responseString = RESP_SUCCESS; boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { try { ServletFileUpload x = new ServletFileUpload(new DiskFileItemFactory()); List<FileItem> items = x.parseRequest(request); for (FileItem item : items) { InputStream input = item.getInputStream(); // Handle a form field. if (item.isFormField()) { String attribute = item.getFieldName(); String value = Streams.asString(input); switch (attribute) { case "chunks": this.chunks = Integer.parseInt(value); break; case "chunk": this.chunk = Integer.parseInt(value); break; case "filename": file.setName(value); break; case "docId": if (value.isEmpty()) { throw new org.apache.commons.fileupload.FileUploadException( "No foi informado o id do documento."); } docId = Integer.parseInt(value); docPath = Config.FILE_PATH + "/" + docId; File documentPath = new File(docPath); // cria o diretorio documentPath.mkdirs(); break; default: break; } } // Handle a multi-part MIME encoded file. else { try { File uploadFile = new File(docPath, item.getName()); BufferedOutputStream bufferedOutput; bufferedOutput = new BufferedOutputStream(new FileOutputStream(uploadFile, true)); byte[] data = item.get(); bufferedOutput.write(data); bufferedOutput.close(); } catch (Exception e) { LOG.error("Erro ao salvar o arquivo.", e); file = null; throw e; } finally { if (input != null) { try { input.close(); } catch (IOException e) { LOG.error("Erro ao fechar o ImputStream", e); } } file.setName(item.getName()); file.setContentType(item.getContentType()); file.setPartialSize(item.getSize()); } } } if ((this.chunk == this.chunks - 1) || this.chunks == 0) { file.setLocation(docPath + "/" + file.getName()); if (docId != null) { file.setDocument(documentsService.get(docId)); } fileService.save(file); file = null; } } catch (org.apache.commons.fileupload.FileUploadException | IOException | NumberFormatException e) { responseString = RESP_ERROR; LOG.error("Erro ao salvar o arquivo", e); file = null; throw e; } } // Not a multi-part MIME request. else { responseString = RESP_ERROR; } response.setContentType("application/json"); byte[] responseBytes = responseString.getBytes(); response.setContentLength(responseBytes.length); ServletOutputStream output = response.getOutputStream(); output.write(responseBytes); output.flush(); return responseString; }
From source file:com.ibm.btt.sample.SampleFileHandler.java
/** * NOTES: In this sample, we just handle the first file item in the upload request. * //from ww w. j a v a 2 s . c om * @param request * @param fileItems upload file items * @return the first file item or null if errors */ private FileItem getTheFileItem(HttpServletRequest request, List<FileItem> fileItems) { String name = ""; for (FileItem fileItem : fileItems) { //common form item name name = fileItem.getFieldName(); if (fileItem.isFormField()) { // common form item value String value = fileItem.getString(); if (LOG.doDebug()) { LOG.debug(new StringBuilder().append("Request item -- ").append(name).append(": ").append(value) .toString()); } } else { if (name == null || "".equals(name.trim())) { continue; } return fileItem; } } return null; }