List of usage examples for org.apache.commons.fileupload FileItem write
void write(File file) throws Exception;
From source file:com.useeasy.auction.util.upload.SimpleUploaderServlet.java
/** * Manage the Upload requests.<br> * /*from w ww . j a va2 s. com*/ * 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. * */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (debug) System.out.println("--- BEGIN DOPOST ---"); 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 + typeStr; String currentDirPath = getServletContext().getRealPath(currentPath); currentPath = request.getContextPath() + currentPath; if (debug) System.out.println(currentDirPath); String retVal = "0"; String newName = ""; String fileUrl = ""; String errorMessage = ""; if (enabled) { DiskFileUpload upload = new 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); if (extIsAllowed(typeStr, ext)) { SimpleDateFormat format = new SimpleDateFormat("yyMMddHHmmssSSS"); newName = format.format(new Date()) + String.valueOf(((int) (Math.random() * 100000))) + "." + ext; fileUrl = currentPath + "/" + newName; pathToSave = new File(currentDirPath, newName); uplFile.write(pathToSave); } else { retVal = "202"; errorMessage = ""; if (debug) System.out.println("Invalid file type: " + ext); } } 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(); if (debug) System.out.println("--- END DOPOST ---"); }
From source file:cpabe.controladores.UploadDownloadFileAdvancedServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (!ServletFileUpload.isMultipartContent(request)) { throw new ServletException("Content type is not multipart/form-data"); }/*from ww w .j a v a 2 s . com*/ // response.setContentType("text/html"); // PrintWriter out = response.getWriter(); // out.write("<html><head></head><body>"); try { List<FileItem> fileItemsList = uploader.parseRequest(request); Iterator<FileItem> fileItemsIterator = fileItemsList.iterator(); while (fileItemsIterator.hasNext()) { FileItem fileItem = fileItemsIterator.next(); System.out.println("FieldName=" + fileItem.getFieldName()); System.out.println("FileName=" + fileItem.getName()); System.out.println("ContentType=" + fileItem.getContentType()); System.out.println("Size in bytes=" + fileItem.getSize()); File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator + fileItem.getName()); //setar no objeto CaminhoArquivo os dados do arquivo anexado String caminho = file.getAbsolutePath(); String nome = fileItem.getName(); CaminhoArquivo c = new CaminhoArquivo(); c.setNome(nome); c.setWay(caminho); request.setAttribute("caminho", c); System.out.println("caminho=" + caminho); System.out.println("nome=" + nome); System.out.println("Absolute Path at server=" + file.getAbsolutePath()); fileItem.write(file); request.getRequestDispatcher("/avancado/encriptar/encriptar1.jsp").forward(request, response); // out.write("File " + fileItem.getName() + " uploaded successfully."); // out.write("<br>"); // out.write("<a href=\"UploadDownloadFileServlet?fileName=" + fileItem.getName() + "\">Download " + fileItem.getName() + "</a>"); } } catch (FileUploadException e) { // out.write("Exception in uploading file."); } catch (Exception e) { // out.write("Exception in uploading file."); } // out.write("</body></html>"); }
From source file:cpabe.controladores.UploadDownloadFileServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (!ServletFileUpload.isMultipartContent(request)) { throw new ServletException("Content type is not multipart/form-data"); }//from w w w .j a v a 2s .com // response.setContentType("text/html"); // PrintWriter out = response.getWriter(); // out.write("<html><head></head><body>"); try { List<FileItem> fileItemsList = uploader.parseRequest(request); Iterator<FileItem> fileItemsIterator = fileItemsList.iterator(); while (fileItemsIterator.hasNext()) { FileItem fileItem = fileItemsIterator.next(); System.out.println("FieldName=" + fileItem.getFieldName()); System.out.println("FileName=" + fileItem.getName()); System.out.println("ContentType=" + fileItem.getContentType()); System.out.println("Size in bytes=" + fileItem.getSize()); File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator + fileItem.getName()); //setar no objeto CaminhoArquivo os dados do arquivo anexado String caminho = file.getAbsolutePath(); String nome = fileItem.getName(); CaminhoArquivo c = new CaminhoArquivo(); c.setNome(nome); c.setWay(caminho); request.setAttribute("caminho", c); System.out.println("caminho=" + caminho); System.out.println("nome=" + nome); System.out.println("Absolute Path at server=" + file.getAbsolutePath()); fileItem.write(file); request.getRequestDispatcher("/formularios/encriptar/encriptar1.jsp").forward(request, response); // out.write("File " + fileItem.getName() + " uploaded successfully."); // out.write("<br>"); // out.write("<a href=\"UploadDownloadFileServlet?fileName=" + fileItem.getName() + "\">Download " + fileItem.getName() + "</a>"); } } catch (FileUploadException e) { // out.write("Exception in uploading file."); } catch (Exception e) { // out.write("Exception in uploading file."); } // out.write("</body></html>"); }
From source file:hoot.services.controllers.ingest.FileUploadResourceTest.java
@Ignore @Test//from w w w. j ava 2s .com @Category(UnitTest.class) public void TestserializeUploadedFiles() throws Exception { FileUploadResource res = new FileUploadResource(); //homeFolder + "/upload/" + jobId + "/" + relPath; // Create dummy FGDB String jobId = "123-456-789-testosm"; String wkdirpath = homeFolder + "/upload/" + jobId; File workingDir = new File(wkdirpath); FileUtils.forceMkdir(workingDir); org.junit.Assert.assertTrue(workingDir.exists()); List<FileItem> fileItemsList = new ArrayList<FileItem>(); FileItemFactory factory = new DiskFileItemFactory(16, null); String textFieldName = "textField"; FileItem item = factory.createItem(textFieldName, "application/octet-stream", true, "dummy1.osm"); String textFieldValue = "0123456789"; byte[] testFieldValueBytes = textFieldValue.getBytes(); OutputStream os = item.getOutputStream(); os.write(testFieldValueBytes); os.close(); File out = new File(wkdirpath + "/buffer.tmp"); item.write(out); fileItemsList.add(item); org.junit.Assert.assertTrue(out.exists()); /* Map<String,String> uploadedFiles = new HashMap<String, String>(); Map<String,String> uploadedFilesPaths = new HashMap<String, String>(); res._serializeUploadedFiles(fileItemsList, jobId, uploadedFiles, uploadedFilesPaths, wkdirpath); org.junit.Assert.assertEquals("OSM", uploadedFiles.get("dummy1")); org.junit.Assert.assertEquals("dummy1.osm", uploadedFilesPaths.get("dummy1")); File content = new File(wkdirpath + "/dummy1.osm"); org.junit.Assert.assertTrue(content.exists()); FileUtils.forceDelete(workingDir);*/ }
From source file:fr.cnes.sitools.proxy.AbstractDirectoryServerResource.java
/** * upload//from ww w. j a va2 s . co m * * @param entity * Representation * @return Representation */ public final Representation upload(Representation entity) { boolean unzip = false; if (this.getDirectory().isModifiable()) { if ((entity != null) && (entity.getMediaType() != null) && (entity.getMediaType().getName().startsWith(MediaType.MULTIPART_FORM_DATA.getName()))) { // 1/ Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1000240); // 2/ Create a new file upload handler based on the Restlet // FileUpload extension that will parse Restlet requests and // generates FileItems. RestletFileUpload upload = new RestletFileUpload(factory); List<FileItem> items; ArrayList<File> zipFiles = new ArrayList<File>(); try { // 3/ Request is parsed by the handler which generates a // list of FileItems items = upload.parseRequest(getRequest()); String path = getDirectory().getRootRef().getPath() + getRelativePart(); String repertoire = Reference.decode(path); // Process only the uploaded item called "fileToUpload" and // save it on disk for (final Iterator<FileItem> it = items.iterator(); it.hasNext();) { FileItem fi = (FileItem) it.next(); if ((fi != null) && (fi.getName() != null)) { // Adding url relative part to post at the real url (not only root directory) File file = new File(repertoire, fi.getName()); fi.write(file); if (file.getName().matches("([^\\s]+(\\.(?i)(zip|ZIP))$)")) { zipFiles.add(file); } } else { if (fi.getFieldName().equals("wantUnzipFile")) { unzip = true; } } } // 4 unzip files if a part is wantUnzipFile if (unzip) { for (File file : zipFiles) { String fileName = file.getName(); int end = fileName.lastIndexOf("."); String name = fileName.substring(0, end); FileCopyUtils.unzipAFile(file.getAbsolutePath(), repertoire + name); } } } catch (FileUploadException e) { getLogger().log(Level.INFO, null, e); getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); } catch (Exception e) { getLogger().log(Level.INFO, null, e); getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); } // String redirectUrl = getReference().toString(); // address of newly created resource // getResponse().redirectSeeOther(redirectUrl); setStatus(Status.SUCCESS_CREATED); } else { // Transfer of PUT calls is only allowed if the readOnly flag is // not set. Request contextRequest = new Request(Method.PUT, this.getTargetUri()); // Add support of partial PUT calls. contextRequest.getRanges().addAll(getRanges()); contextRequest.setEntity(entity); Response contextResponse = new Response(contextRequest); contextRequest.setResourceRef(this.getTargetUri()); getClientDispatcher().handle(contextRequest, contextResponse); setStatus(contextResponse.getStatus()); } } else { setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED, "The directory is not modifiable."); } return null; }
From source file:de.suse.swamp.modules.actions.WorkflowActions.java
/** * Store the uploaded workflow to a temp. directory and verify it */// ww w. ja v a 2 s .c om public void doUploadworkflow(RunData data, Context context) throws Exception { org.apache.turbine.util.parser.ParameterParser pp = data.getParameters(); String separator = System.getProperty("file.separator"); String tmpdir = System.getProperty("java.io.tmpdir"); ArrayList results = new ArrayList(); // storing file FileItem fi = pp.getFileItem("filename"); if (fi == null || fi.getName() == null || fi.getSize() == 0) { throw new Exception("Empty file uploaded."); } if (fi.getName().endsWith(".xml") || fi.getName().endsWith(".zip")) { String uniqueid = String.valueOf(new Date().getTime()); String basePath = tmpdir + separator + uniqueid; FileUtils.forceMkdir(new File(basePath)); WorkflowReadResult result = null; if (fi.getName().endsWith("xml")) { File wfTmpFile = new File(basePath + separator + "workflow.xml"); if (wfTmpFile.exists()) { wfTmpFile.delete(); } fi.write(wfTmpFile); if (!wfTmpFile.exists()) { throw new Exception("Storing of file: " + fi.getName() + " failed."); } } else { // unpack uploaded workflow resource bundle de.suse.swamp.util.FileUtils.uncompress(fi.getInputStream(), basePath); } // read + verify the workflow: WorkflowReader reader = new WorkflowReader(new File(basePath)); result = reader.readWorkflow(basePath); results.add(result); context.put("uniqueid", uniqueid); // clean uploaded stuff on errors if (result.hasErrors()) { FileUtils.deleteDirectory(new File(basePath)); } } else { throw new Exception( "Only upload of single \"workflow.xml\" and \".zip\" packed workflow bundles is supported."); } context.put("workflowreadresults", results); }
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 ava2 s .com*/ // 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:com.colegiocefas.cefasrrhh.servlets.subirCurriculo.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request//from www.j a va 2s . c om * @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 { String dui = request.getParameter("dui"); String nombre = request.getParameter("nombre"); String especialidad = request.getParameter("especialidad"); String url = request.getParameter("url"); //Cdigo para subir pdf del curriculum al servidor try { List items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (int i = 0; i < items.size(); i++) { FileItem item = (FileItem) items.get(i); if (item.isFormField()) { if (item.getFieldName().equals("dui")) dui = item.getString("UTF-8"); if (item.getFieldName().equals("especialidad")) especialidad = item.getString("UTF-8"); if (item.getFieldName().equals("nombre")) nombre = item.getString("UTF-8"); } else { Date fecha = Calendar.getInstance().getTime(); SimpleDateFormat formato = new SimpleDateFormat("yyyyMMdd-hhmmss-"); String nombreImagen = formato.format(fecha); nombreImagen += dui; //String fileName = item.getName(); response.setContentType("text/plain"); response.setCharacterEncoding("UTF-8"); String realPath = request.getSession().getServletContext().getRealPath("/"); File fichero = new File(realPath + "documentos/candidatos/", nombreImagen + ".pdf"); item.write(fichero); url = "documentos/candidatos/" + fichero.getName(); } } CtrlCEFAS_Candidato ctrlcandidato = new CtrlCEFAS_Candidato(); ctrlcandidato.guardarCurriculum(dui, nombre, Integer.parseInt(especialidad), url); String mensaje = "<div class='alert alert-success' role='alert'>Guardado</div>"; response.sendRedirect("ingresarcurriculum.jsp"); } catch (Exception e) { //out.write(e.getMessage()); //JOptionPane.showMessageDialog(null, e.getMessage()); throw new ServletException("Parsing file upload failed.", e); } }
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 w w . ja v a 2s . c om*/ 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() + "\""); } }
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();/*from w w w . j a v a 2s . 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"); }