List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory setRepository
public void setRepository(File repository)
From source file:isl.FIMS.servlet.imports.ImportVocabulary.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.initVars(request); String username = getUsername(request); Config conf = new Config("AdminVoc"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); StringBuilder xml = new StringBuilder( this.xmlStart(this.topmenu, username, this.pageTitle, this.lang, "", request)); String file = request.getParameter("file"); if (ServletFileUpload.isMultipartContent(request)) { // configures some settings String filePath = this.export_import_Folder; java.util.Date date = new java.util.Date(); Timestamp t = new Timestamp(date.getTime()); String currentDir = filePath + t.toString().replaceAll(":", ""); File saveDir = new File(currentDir); if (!saveDir.exists()) { saveDir.mkdir();// www . ja v a2s . c o m } DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD); factory.setRepository(saveDir); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(REQUEST_SIZE); // constructs the directory path to store upload file String uploadPath = currentDir; try { // parses the request's content to extract file data List formItems = upload.parseRequest(request); Iterator iter = formItems.iterator(); // iterates over form's fields File storeFile = null; 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(); filePath = uploadPath + File.separator + fileName; storeFile = new File(filePath); // saves the file on disk item.write(storeFile); } } ArrayList<String> content = Utils.readFile(storeFile); DMSConfig vocConf = new DMSConfig(this.DBURI, this.systemDbCollection + "Vocabulary/", this.DBuser, this.DBpassword); Vocabulary voc = new Vocabulary(file, this.lang, vocConf); String[] terms = voc.termValues(); for (int i = 0; i < content.size(); i++) { String addTerm = content.get(i); if (!Arrays.asList(terms).contains(addTerm)) { voc.addTerm(addTerm); } } Utils.deleteDir(currentDir); response.sendRedirect("AdminVoc?action=list&file=" + file + "&menuId=AdminVoc"); } catch (Exception ex) { } } xml.append("<FileName>").append(file).append("</FileName>\n"); xml.append("<EntityType>").append("AdminVoc").append("</EntityType>\n"); xml.append(this.xmlEnd()); String xsl = conf.IMPORT_Vocabulary; try { XMLTransform xmlTrans = new XMLTransform(xml.toString()); xmlTrans.transform(out, xsl); } catch (DMSException e) { e.printStackTrace(); } out.close(); }
From source file:com.shyshlav.functions.filework.download_image.java
public String download(HttpServletRequest request, HttpServletResponse response) throws IOException { request.setCharacterEncoding("UTF-8"); // response.setCharacterEncoding("UTF-8"); filePath = request.getSession().getServletContext().getInitParameter("avathars"); System.out.println(filePath); isMultipart = ServletFileUpload.isMultipartContent(request); System.out.println(isMultipart); response.setContentType("text/html"); PrintWriter out = response.getWriter(); if (!isMultipart) { return " "; }// ww w . j a v a2 s .c o m 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:\test")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); try { // Parse the request to get file items. List<FileItem> fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); //String name,String password,String email,String surname,String link_to_image,String about_me,String id String name = null; String password = null; String re_password = null; String surname = null; String about_me = null; String id = null; String link_to_server = null; String email = null; while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (fi.isFormField()) { String fieldname = fi.getFieldName(); String fieldvalue = fi.getString(); if (fieldname.equals("name")) { name = fi.getString("UTF-8"); } else if (fieldname.equals("surname")) { surname = fi.getString("UTF-8"); } else if (fieldname.equals("password")) { password = fi.getString("UTF-8"); } else if (fieldname.equals("re_password")) { re_password = fi.getString("UTF-8"); } else if (fieldname.equals("about_me")) { about_me = fi.getString("UTF-8"); } else if (fieldname.equals("id")) { id = fi.getString("UTF-8"); } else if (fieldname.equals("email")) { email = fi.getString("UTF-8"); } System.out.println(fieldname + fieldvalue); if (fieldname == null || fieldvalue == null) { return "? ? ? "; } } if (!fi.isFormField()) { if (!password.equals(re_password)) { System.out.println(password + " - " + re_password); return " ?"; } // Get the uploaded file parameters String fileName = email + ".png"; link_to_server = "/musicbox/avathars/" + email + ".png".trim(); // 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); System.out.println("Uploaded Filename: " + filePath + fileName); } } System.out.println(link_to_server); updateUser um = new updateUser(); um.updateUser(name, password, surname, link_to_server, about_me, id); } catch (Exception ex) { System.out.println(ex); return " 1 "; } return "ok"; }
From source file:eu.stratuslab.storage.disk.resources.DisksResource.java
private Disk saveAndInflateFiles() { int fileSizeLimit = ServiceConfiguration.getInstance().UPLOAD_COMPRESSED_IMAGE_MAX_BYTES; DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(FileUtils.getUploadCacheDirectory()); factory.setSizeThreshold(fileSizeLimit); RestletFileUpload upload = new RestletFileUpload(factory); List<FileItem> items = null; try {/*from w w w .j a v a2 s . c o m*/ items = upload.parseRequest(getRequest()); } catch (FileUploadException e) { throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, e.getMessage()); } FileItem lastFileItem = null; for (FileItem fi : items) { if (fi.getName() != null) { lastFileItem = fi; } } for (FileItem fi : items) { if (fi != lastFileItem) { fi.delete(); } } if (lastFileItem != null) { return inflateAndProcessImage(lastFileItem); } else { throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "empty file uploaded"); } }
From source file:com.esri.gpt.control.filter.MultipartWrapper.java
/** * Construct with a current HTTP servlet request. * @param request the current HTTP servlet request * @throws FileUploadException if an exception occurs during file upload *///from ww w .j a v a2 s . c o m public MultipartWrapper(HttpServletRequest request) throws FileUploadException { super(request); getLogger().finer("Handling multipart content."); // initialize parameters _fileParameters = new HashMap<String, FileItem>(); _formParameters = new HashMap<String, String[]>(); int nFileSizeMax = 100000000; int nSizeThreshold = 500000; String sTmpFolder = ""; // make the file item factory DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(nSizeThreshold); if (sTmpFolder.length() > 0) { File fTmpFolder = new File(sTmpFolder); factory.setRepository(fTmpFolder); } // make the file upload object ServletFileUpload fileUpload = new ServletFileUpload(); fileUpload.setFileItemFactory(factory); fileUpload.setFileSizeMax(nFileSizeMax); // parse the parameters associated with the request List items = fileUpload.parseRequest(request); String[] aValues; ArrayList<String> lValues; for (int i = 0; i < items.size(); i++) { FileItem item = (FileItem) items.get(i); getLogger().finer("FileItem=" + item); if (item.isFormField()) { String sName = item.getFieldName(); String sValue = item.getString(); if (_formParameters.containsKey(sName)) { aValues = _formParameters.get(sName); lValues = new ArrayList<String>(Arrays.asList(aValues)); lValues.add(sValue); aValues = lValues.toArray(new String[0]); } else { aValues = new String[1]; aValues[0] = sValue; } _formParameters.put(sName, aValues); } else { _fileParameters.put(item.getFieldName(), item); request.setAttribute(item.getFieldName(), item); } } }
From source file:hu.sztaki.lpds.submitter.service.jobstatus.JobStatusServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request/* www. j av a 2 s .co 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 { //System.out.println("JobStatusServlet.processRequest called !!!!!!!!!!!!!!!"); String uid = ""; String jobid = ""; int status = -1; //sysLog(jobid, "JobStatusServlet * * * JobStatusServlet called"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); fileItemFactory.setSizeThreshold(30 * 1024 * 1024); //1 MB fileItemFactory.setRepository(new File(Base.getI().getPath()));//new File() ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); try { List items = uploadHandler.parseRequest(request); Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); if (item.isFormField()) { // out.println("Field Name = " + item.getFieldName() + ", Value = " + item.getString()); // System.out.println("JobStatusServlet: Field Name = " + item.getFieldName() + ", Value = " + item.getString()); if ("uid".equals("" + item.getFieldName())) { uid = item.getString(); } else if ("jobid".equals("" + item.getFieldName())) { jobid = item.getString(); } else if ("status".equals("" + item.getFieldName())) { status = Integer.parseInt(item.getString()); } } else { // System.out.println("JobStatusServlet: Field Name = " + item.getFieldName() // + ", File Name = " + item.getName() // + ", Content type = " + item.getContentType() // + ", File Size = " + item.getSize()); // out.println("Field Name = " + item.getFieldName() // + ", File Name = " + item.getName() // + ", Content type = " + item.getContentType() // + ", File Size = " + item.getSize()); // outfiles.add(item.getName()); if (status == 1 && GStatusHandler.getI().setStatus(uid, jobid, status)) {//if status == uploading(1) and userid->jobid File destinationDir = new File(Base.getI().getPath() + jobid + "/outputs"); File file = new File(destinationDir, item.getName()); item.write(file); } else { System.out.println("ILLEGAL ACCESS or Deleted job!? uid:" + uid + " jobid:" + jobid); } } } } catch (FileUploadException ex) { sysLog(jobid, "JobStatusServlet: Error encountered while parsing the request: " + ex + " --> try getparameters"); //ex.printStackTrace(); uid = request.getParameter("uid"); jobid = request.getParameter("jobid"); try { if (request.getParameter("status") != null) { status = Integer.parseInt(request.getParameter("status")); if (status == 6) { status = 66; } else if (status == 7) { status = 77; } //running status = 55 } } catch (Exception ee) { //ee.printStackTrace(); } } catch (Exception ex) { sysLog(jobid, "JobStatusServlet:Error encountered while uploading file: " + ex); //ex.printStackTrace(); } sysLog(jobid, " JobStatusServlet: status=" + status + " userid=" + uid); if (status != -1) { GStatusHandler.getI().setStatus(uid, jobid, status); } //RequestDispatcher comp = null; //comp = request.getRequestDispatcher("hiba.jsp"); // comp.forward(request, response); } catch (Exception ee) { ee.printStackTrace(); } finally { out.close(); } //GStatusHandler.getI().getJob(jobID) }
From source file:controlador.SerPartido.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); //ruta relativa en donde se guardan las imagenes de partidos String ruta = getServletContext().getRealPath("/") + "images/files/banderas/";//imagenes de los partidos politicos Partido p = new Partido(); int accion = 1; //1=gregar 2=modificar if (ServletFileUpload.isMultipartContent(request)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setSizeThreshold(40960); File repositoryPath = new File("/temp"); diskFileItemFactory.setRepository(repositoryPath); ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); servletFileUpload.setSizeMax(81920); // bytes upload.setSizeMax(307200); // 1024 x 300 = 307200 bytes = 300 Kb List listUploadFiles = null; FileItem item = null;/*from ww w . ja va 2s . c o m*/ try { listUploadFiles = upload.parseRequest(request); Iterator it = listUploadFiles.iterator(); while (it.hasNext()) { item = (FileItem) it.next(); if (!item.isFormField()) { if (item.getSize() > 0) { String nombre = item.getName(); String tipo = item.getContentType(); long tamanio = item.getSize(); String extension = nombre.substring(nombre.lastIndexOf(".")); File archivo = new File(ruta, nombre); item.write(archivo); if (archivo.exists()) { p.setImagen(nombre); } else { out.println("FALLO AL GUARDAR. NO EXISTE " + archivo.getAbsolutePath() + "</p>"); } } } else { //se reciben los campos de texto enviados y se igualan a los atributos del objeto if (item.getFieldName().equals("txtAcronimo")) { p.setAcronimo(item.getString()); } if (item.getFieldName().equals("txtNombre")) { p.setNombre(item.getString()); } if (item.getFieldName().equals("txtDui")) { p.setNumDui(item.getString()); } if (item.getFieldName().equals("txtId")) { p.setIdPartido(Integer.parseInt(item.getString())); } } } //si no se selecciono una imagen distinta, se conserva la imagen anterior if (p.getImagen() == null) { p.setImagen(PartidoDTO.mostrarPartido(p.getIdPartido()).getImagen()); } //cuando se presiona el boton de agregar if (p.getIdPartido() == 0) { if (PartidoDTO.agregarPartido(p)) { response.sendRedirect(this.redireccionJSP); } else { //cambiar por alguna accion en caso de error out.print("Error al insertar"); } } //cuando se presiona el boton de modificar else { if (PartidoDTO.modificarPartido(p)) { response.sendRedirect(this.redireccionJSP); } else { out.print("Error al modificar"); } } } catch (FileUploadException e) { out.println("Error Upload: " + e.getMessage()); e.printStackTrace(); } catch (Exception e) { out.println("Error otros: " + e.getMessage()); e.printStackTrace(); } } }
From source file:com.assignment.elance.controller.FileUploadServlet.java
/** * Upon receiving file upload submission, parses the request to read upload * data and saves the file on disk./*w w w. ja v a 2s . co m*/ */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // checks if the request actually contains upload file if (!ServletFileUpload.isMultipartContent(request)) { // if not, we stop here PrintWriter writer = response.getWriter(); writer.println("Error: Form must has enctype=multipart/form-data."); writer.flush(); return; } // configures upload settings DiskFileItemFactory factory = new DiskFileItemFactory(); // sets memory threshold - beyond which files are stored in disk factory.setSizeThreshold(MEMORY_THRESHOLD); // sets temporary location to store files factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); // sets maximum size of upload file upload.setFileSizeMax(MAX_FILE_SIZE); // sets maximum size of request (include file + form data) upload.setSizeMax(MAX_REQUEST_SIZE); // constructs the directory path to store upload file // this path is relative to application's directory String uploadPath = getServletContext().getRealPath("") + File.separator + SystemAttributes.UPLOAD_DIRECTORY; // creates the directory if it does not exist File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdir(); } try { // parses the request's content to extract file data @SuppressWarnings("unchecked") List<FileItem> formItems = upload.parseRequest(request); if (formItems != null && formItems.size() > 0) { // iterates over form's fields for (FileItem item : formItems) { // processes only fields that are not form fields if (!item.isFormField()) { String fileName = new File(item.getName()).getName(); String file = randomFileNameGenerator(); String filePath = uploadPath + File.separator + file; File storeFile = new File(filePath); // saves the file on disk item.write(storeFile); FilesManager fm = new FilesManager(); boolean send_dir = false; switch (Integer.parseInt(request.getParameter("senddir"))) { case 0: send_dir = false; break; case 1: send_dir = true; break; } fm.insert(fileName, file, Integer.parseInt(request.getParameter("jobId")), send_dir); request.setAttribute("message", "Upload has been done successfully!"); } } } } catch (Exception ex) { request.setAttribute("message", "There was an error: " + ex.getMessage()); } // // redirects client to message page // getServletContext().getRequestDispatcher("/message.jsp").forward( // request, response); switch (Integer.parseInt(request.getParameter("callbackpage"))) { case 0: response.sendRedirect("projectOverview.jsp?pId=" + Integer.parseInt(request.getParameter("jobId"))); break; case 1: response.sendRedirect("project.jsp?jobId=" + Integer.parseInt(request.getParameter("jobId"))); break; } }
From source file:business.controllers.UploadImageController.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (!ServletFileUpload.isMultipartContent(request)) { PrintWriter writer = response.getWriter(); writer.println("Request does not contain upload data"); writer.flush();//from w w w. j av a2 s .co m return; } String oauthCode = ""; // 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); List formItems = new ArrayList(); try { // parses the request's content to extract file data formItems = upload.parseRequest(request); 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.getFieldName().equals("oauthcode")) { oauthCode = item.getString(); } } } catch (FileUploadException ex) { logger.error("Write image:" + ex); } //checkLogin BusinessChatHandler handler = new BusinessChatHandler(); try { if (handler.isLogin(oauthCode)) { uploadImage(request, response, formItems); } } catch (TException ex) { java.util.logging.Logger.getLogger(UploadImageController.class.getName()).log(Level.SEVERE, null, ex); } }
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 ww w . j av a2 s. 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("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;/* ww w .ja v a2 s . c om*/ 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); }