List of usage examples for org.apache.commons.fileupload FileItem getString
String getString();
From source file:communicator.doMove.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// w ww . j av a2s. 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"); PrintWriter out = null; JSONObject outputObject = new JSONObject(); try { HashMap<String, String> bigItemIds = new HashMap<>(); Iterator mIterator = bigItemIds.keySet().iterator(); out = response.getWriter(); // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Configure a repository (to ensure a secure temp location is used) ServletContext servletContext = this.getServletConfig().getServletContext(); File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir"); factory.setRepository(repository); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List<FileItem> items = upload.parseRequest(request); final String moveId = UUID.randomUUID().toString(); final MovesDb movesDb = new MovesDb(); // Process the uploaded items Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) { System.out.println("Form field" + item.getString()); bigItemIds = processFormField(new JSONObject(item.getString()), out, moveId, movesDb); mIterator = bigItemIds.keySet().iterator(); System.out.println("ITEM ID SIZE " + bigItemIds.size()); } else { //processUploadedFile(item); System.out.print("Photo Field"); String key = (String) mIterator.next(); File mFile = new File(bigItemIds.get(key)); item.write(mFile); } } new Thread() { public void run() { pushMovetoMailQueue moveToMailQueue = new pushMovetoMailQueue(); moveToMailQueue.pushMoveToMailQueue(movesDb); } }.start(); outputObject = new JSONObject(); try { outputObject.put(Constants.JSON_STATUS, Constants.JSON_SUCCESS); outputObject.put(Constants.JSON_MSG, Constants.JSON_GET_QUOTE); } catch (JSONException ex1) { Logger.getLogger(doSignUp.class.getName()).log(Level.SEVERE, null, ex1); } out.println(outputObject.toString()); } catch (Exception ex) { outputObject = new JSONObject(); try { outputObject.put(Constants.JSON_STATUS, Constants.JSON_FAILURE); outputObject.put(Constants.JSON_MSG, Constants.JSON_EXCEPTION); } catch (JSONException ex1) { Logger.getLogger(doSignUp.class.getName()).log(Level.SEVERE, null, ex1); } out.println(outputObject.toString()); Logger.getLogger(doSignUp.class.getName()).log(Level.SEVERE, null, ex); } finally { out.close(); } }
From source file:crds.pub.FCKeditor.uploader.SimpleUploaderServlet.java
/** * Manage the Upload requests.<br> * * The servlet accepts commands sent in the following format:<br> * simpleUploader?Type=ResourceType<br><br> * It store the file (renaming it in case a file with the same name exists) and then return an HTML file * with a javascript command in it.//from www . j a v a 2s . c o m * */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); FormUserOperation formUser = Constant.getFormUserOperation(request); String fck_task_id = (String) request.getSession().getAttribute("fck_task_id"); if (fck_task_id == null) { fck_task_id = "temp_task_id"; } response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String typeStr = request.getParameter("Type"); String currentPath = baseDir + formUser.getCompany_code() + "/" + fck_task_id + "/" + typeStr; String currentDirPath = getServletContext().getRealPath(currentPath); File currentDir = new File(currentDirPath); if (!currentDir.exists()) { currentDir.mkdirs(); } String retVal = "0"; String newName = ""; String fileUrl = ""; String errorMessage = ""; if (enabled) { org.apache.commons.fileupload.DiskFileUpload upload = new org.apache.commons.fileupload.DiskFileUpload(); try { List items = upload.parseRequest(request); Map fields = new HashMap(); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) fields.put(item.getFieldName(), item.getString()); else fields.put(item.getFieldName(), item); } FileItem uplFile = (FileItem) fields.get("NewFile"); String fileNameLong = uplFile.getName(); fileNameLong = fileNameLong.replace('\\', '/'); String[] pathParts = fileNameLong.split("/"); String fileName = pathParts[pathParts.length - 1]; String nameWithoutExt = getNameWithoutExtension(fileName); String ext = getExtension(fileName); File pathToSave = new File(currentDirPath, fileName); //???IP String server_ip = (String) session.getAttribute("server_ip"); if (server_ip == null) { server_ip = CommonMethod.getServerIP(request) + ":" + request.getServerPort();//???IP? } String url = "http://" + server_ip + currentPath.substring(2, currentPath.length()); fileUrl = url + "/" + fileName; if (extIsAllowed(typeStr, ext)) { int counter = 1; while (pathToSave.exists()) { newName = nameWithoutExt + "(" + counter + ")" + "." + ext; fileUrl = url + "/" + newName; retVal = "201"; pathToSave = new File(currentDirPath, newName); counter++; } uplFile.write(pathToSave); } else { retVal = "202"; errorMessage = ""; } } catch (Exception ex) { if (debug) ex.printStackTrace(); retVal = "203"; } } else { retVal = "1"; errorMessage = "This file uploader is disabled. Please check the WEB-INF/web.xml file"; } out.println("<script type=\"text/javascript\">"); out.println("window.parent.OnUploadCompleted(" + retVal + ",'" + fileUrl + "','" + newName + "','" + errorMessage + "');"); out.println("</script>"); out.flush(); out.close(); }
From source file:edu.lafayette.metadb.web.dataman.ImportAdminDesc.java
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */// w ww . ja v a 2 s . c om @SuppressWarnings("unchecked") protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub PrintWriter out = response.getWriter(); String delimiter = "comma"; boolean replaceEntity = false; String projname = (String) request.getSession(false).getAttribute(Global.SESSION_PROJECT); JSONObject output = new JSONObject(); try { if (ServletFileUpload.isMultipartContent(request)) { ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory()); List fileItemsList = servletFileUpload.parseRequest(request); DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setSizeThreshold(40960); /* the unit is bytes */ Iterator it = fileItemsList.iterator(); InputStream input = null; while (it.hasNext()) { FileItem fileItem = (FileItem) it.next(); if (fileItem.isFormField()) { /* The file item contains a simple name-value pair of a form field */ if (fileItem.getFieldName().equals("delimiter")) delimiter = fileItem.getString(); else if (fileItem.getFieldName().equals("replace-entity")) replaceEntity = true; } else { input = fileItem.getInputStream(); } } String delimiterType = "csv"; if (delimiter.equals("tab")) { delimiterType = "tsv"; } if (input != null) { Result res = DataImporter.importFile(delimiterType, projname, input, replaceEntity); if (res.isSuccess()) { HttpSession session = request.getSession(false); if (session != null) { String userName = (String) session.getAttribute(Global.SESSION_USERNAME); SysLogDAO.log(userName, Global.SYSLOG_PROJECT, "Data imported into project " + projname); } output.put("message", "Data import successfully"); } else { output.put("message", "The following fields have been changed:"); StringBuilder fields = new StringBuilder(); for (String field : (ArrayList<String>) res.getData()) fields.append(field + ','); output.put("fields", fields.toString()); } output.put("success", res.isSuccess()); } else { output.put("success", false); output.put("message", "Null data"); } } else { output.put("success", false); output.put("message", "Form is not multi-part"); } } catch (Exception e) { MetaDbHelper.logEvent(e); } out.print(output); out.flush(); }
From source file:com.flipkart.poseidon.core.PoseidonServlet.java
private void handleFileUpload(PoseidonRequest request, HttpServletRequest httpRequest) throws IOException { // If uploaded file size is more than 10KB, will be stored in disk DiskFileItemFactory factory = new DiskFileItemFactory(); File repository = new File(FILE_UPLOAD_TMP_DIR); if (repository.exists()) { factory.setRepository(repository); }/*w w w .j a va2s . c o m*/ // Currently we don't impose max file size at container layer. Apps can impose it by checking FileItem // Apps also have to delete tmp file explicitly (if at all it went to disk) ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> fileItems = null; try { fileItems = upload.parseRequest(httpRequest); } catch (FileUploadException e) { throw new IOException(e); } for (FileItem fileItem : fileItems) { String name = fileItem.getFieldName(); if (fileItem.isFormField()) { request.setAttribute(name, new String[] { fileItem.getString() }); } else { request.setAttribute(name, fileItem); } } }
From source file:it.biblio.servlets.Inserimento_pub.java
/** * metodo per gestire l'upload di file e inserimento pubblicazione con prima * ristampa/*from w ww . j ava 2s.c om*/ * * @param request * @param response * @param k * @return * @throws IOException */ private boolean upload(HttpServletRequest request) throws IOException, Exception { Map<String, Object> pub = new HashMap<String, Object>(); Map<String, Object> ristampe = new HashMap<String, Object>(); Map<String, Object> keyword = new HashMap<String, Object>(); HttpSession s = SecurityLayer.checkSession(request); if (ServletFileUpload.isMultipartContent(request)) { FileItemFactory fif = new DiskFileItemFactory(); ServletFileUpload sfo = new ServletFileUpload(fif); List<FileItem> items = sfo.parseRequest(request); for (FileItem item : items) { String fname = item.getFieldName(); if (item.isFormField() && fname.equals("titolo") && !item.getString().isEmpty()) { pub.put("titolo", item.getString()); pub.put("utente", s.getAttribute("userid")); } else if (item.isFormField() && fname.equals("descrizione") && !item.getString().isEmpty()) { pub.put("descrizione", item.getString()); } else if (item.isFormField() && fname.equals("autore") && !item.getString().isEmpty()) { pub.put("autore", item.getString()); } else if (item.isFormField() && fname.equals("categoria") && !item.getString().isEmpty()) { pub.put("categoria", item.getString()); } else if (item.isFormField() && fname.equals("ISBN") && !item.getString().isEmpty()) { ristampe.put("isbn", item.getString()); } else if (item.isFormField() && fname.equals("numero_pagine") && !item.getString().isEmpty()) { ristampe.put("numpagine", Integer.parseInt(item.getString())); } else if (item.isFormField() && fname.equals("anno_pub") && !item.getString().isEmpty()) { ristampe.put("datapub", item.getString()); } else if (item.isFormField() && fname.equals("editore") && !item.getString().isEmpty()) { ristampe.put("editore", item.getString()); } else if (item.isFormField() && fname.equals("lingua") && !item.getString().isEmpty()) { ristampe.put("lingua", item.getString()); } else if (item.isFormField() && fname.equals("indice") && !item.getString().isEmpty()) { ristampe.put("indice", item.getString()); } else if (item.isFormField() && fname.equals("keyword") && !item.getString().isEmpty()) { keyword.put("tag1", item.getString()); } else if (item.isFormField() && fname.equals("keyword2") && !item.getString().isEmpty()) { keyword.put("tag2", item.getString()); } else if (item.isFormField() && fname.equals("keyword3") && !item.getString().isEmpty()) { keyword.put("tag3", item.getString()); } else if (!item.isFormField() && fname.equals("PDF")) { String name = item.getName(); long size = item.getSize(); if (size > 0 && !name.isEmpty()) { File target = new File(getServletContext().getRealPath("") + File.separatorChar + "PDF" + File.separatorChar + name); item.write(target); ristampe.put("download", "PDF" + File.separatorChar + name); } } else if (!item.isFormField() && fname.equals("copertina")) { String name = item.getName(); long size = item.getSize(); if (size > 0 && !name.isEmpty()) { File target = new File(getServletContext().getRealPath("") + File.separatorChar + "Copertine" + File.separatorChar + name); item.write(target); ristampe.put("copertina", "Copertine" + File.separatorChar + name); } } } Database.insertRecord("keyword", keyword); ResultSet ss = Database.selectRecord("keyword", "tag1='" + keyword.get("tag1") + "' && " + "tag2='" + keyword.get("tag2") + "' && tag3='" + keyword.get("tag3") + "'"); if (!isNull(ss)) { int indicek = 0; while (ss.next()) { indicek = ss.getInt("id"); } pub.put("keyword", indicek); Database.insertRecord("pubblicazioni", pub); ResultSet rs = Database.selectRecord("pubblicazioni", "titolo='" + pub.get("titolo") + "'"); while (rs.next()) { ristampe.put("pubblicazioni", rs.getInt("id")); } return Database.insertRecord("ristampe", ristampe); } else { return false; } } return false; }
From source file:it.vige.greenarea.sgrl.servlet.CommonsFileUploadServlet.java
protected void workingdoPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); response.setContentType("text/plain"); out.println("<h1>Servlet File Upload Example using Commons File Upload</h1>"); out.println();/*from ww w . ja va 2s. c o m*/ 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. */ fileItemFactory.setRepository(tmpDir); ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); try { /* * Parse the request */ List<FileItem> items = uploadHandler.parseRequest(request); Iterator<FileItem> itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); /* * Handle Form Fields. */ if (item.isFormField()) { out.println("File Name = " + item.getFieldName() + ", Value = " + item.getString()); } else { // Handle Uploaded files. out.println("Field Name = " + item.getFieldName() + ", File Name = " + item.getName() + ", Content type = " + item.getContentType() + ", File Size = " + item.getSize()); /* * Write file to the ultimate location. */ File file = new File(destinationDir, "LogisticNetwork.mxe"); item.write(file); } out.close(); } } catch (FileUploadException ex) { log("Error encountered while parsing the request", ex); } catch (Exception ex) { log("Error encountered while uploading file", ex); } }
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(); /*//from w ww. j a va 2s. 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:Atualizar.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { boolean isMultipart = ServletFileUpload.isMultipartContent(req); String caminho;//from ww w. j ava 2 s .co 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.radio.svc.controllers.admin.AddFeatureSSDController.java
@Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { //To change body of generated methods, choose Tools | Templates. String[] ssdFeatures = null;//from ww w .j a v a 2 s. co m FileItem ssdFeatureFile = null; String songName = null; if (ServletFileUpload.isMultipartContent(request)) { try { List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : multiparts) { if (!item.isFormField()) { if (item.getFieldName().equals("ssdFeatureUpload")) { ssdFeatureFile = item; } } else { if (item.getFieldName().equals("songname")) { songName = item.getString(); //System.out.println( "Album Name " + item.getString() ); } } } } catch (Exception e) { e.printStackTrace(); } } ModelAndView model; model = new ModelAndView("/admin/featureSSDAdmin"); model.addObject("controller", "addfeaturessd"); featureSSDServiceProvider.addNewFeatureSSD(songName, ssdFeatureFile); model.addObject("msg", "success"); return model; }
From source file:cn.trymore.core.web.servlet.FileUploadServlet.java
@Override @SuppressWarnings("unchecked") protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); try {/*from w ww . j a v a2 s . c o m*/ DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setSizeThreshold(4096); diskFileItemFactory.setRepository(new File(this.tempPath)); String fileIds = ""; ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); List<FileItem> fileList = (List<FileItem>) servletFileUpload.parseRequest(request); Iterator<FileItem> itor = fileList.iterator(); Iterator<FileItem> itor1 = fileList.iterator(); String file_type = ""; while (itor1.hasNext()) { FileItem item = itor1.next(); if (item.isFormField() && "file_type".equals(item.getFieldName())) { file_type = item.getString(); } } FileItem fileItem; while (itor.hasNext()) { fileItem = itor.next(); if (fileItem.getContentType() == null) { continue; } // obtains the file path and name String filePath = fileItem.getName(); String fileName = filePath.substring(filePath.lastIndexOf("/") + 1); // generates new file name with the current time stamp. String newFileName = this.fileCat + "/" + UtilFile.generateFilename(fileName); // ensure the directory existed before creating the file. File dir = new File( this.uploadPath + "/" + newFileName.substring(0, newFileName.lastIndexOf("/") + 1)); if (!dir.exists()) { dir.mkdirs(); } // stream writes to the destination file fileItem.write(new File(this.uploadPath + "/" + newFileName)); ModelFileAttach fileAttach = null; if (request.getParameter("noattach") == null) { // storages the file into database. fileAttach = new ModelFileAttach(); fileAttach.setFileName(fileName); fileAttach.setFilePath(newFileName); fileAttach.setTotalBytes(Long.valueOf(fileItem.getSize())); fileAttach.setNote(this.getStrFileSize(fileItem.getSize())); fileAttach.setFileExt(fileName.substring(fileName.lastIndexOf(".") + 1)); fileAttach.setCreatetime(new Date()); fileAttach.setDelFlag(ModelFileAttach.FLAG_NOT_DEL); fileAttach.setFileType(!"".equals(file_type) ? file_type : this.fileCat); ModelAppUser user = ContextUtil.getCurrentUser(); if (user != null) { fileAttach.setCreatorId(Long.valueOf(user.getId())); fileAttach.setCreator(user.getFullName()); } else { fileAttach.setCreator("Unknow"); } this.serviceFileAttach.save(fileAttach); } //add by Tang ??fileIds????? if (fileAttach != null) { fileIds = (String) request.getSession().getAttribute("fileIds"); if (fileIds == null) { fileIds = fileAttach.getId(); } else { fileIds = fileIds + "," + fileAttach.getId(); } } response.setContentType("text/html;charset=UTF-8"); PrintWriter writer = response.getWriter(); writer.println( "{\"status\": 1, \"data\":{\"id\":" + (fileAttach != null ? fileAttach.getId() : "\"\"") + ", \"url\":\"" + newFileName + "\"}}"); } request.getSession().setAttribute("fileIds", fileIds); } catch (Exception e) { e.printStackTrace(); response.getWriter().write("{\"status\":0, \"message\":\":" + e.getMessage() + "\""); } }