List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory DiskFileItemFactory
public DiskFileItemFactory()
From source file:com.colegiocefas.cefasrrhh.servlets.subirImagen.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request//from w ww . j a va 2s .c o m * @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 ajaxUpdateResult = "Error"; 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()) { } else { Date fecha = Calendar.getInstance().getTime(); SimpleDateFormat formato = new SimpleDateFormat("yyyyMMdd-hhmmss-"); String nombreImagen = formato.format(fecha); HttpSession sesionOk = request.getSession(); String usuario = (String) sesionOk.getAttribute("usuario"); if (usuario == null) { request.getRequestDispatcher("index.jsp").forward(request, response); return; } nombreImagen += usuario; //String fileName = item.getName(); response.setContentType("text/plain"); response.setCharacterEncoding("UTF-8"); String realPath = request.getSession().getServletContext().getRealPath("/"); File fichero = new File(realPath + "img/fotos/", nombreImagen + ".png"); item.write(fichero); ajaxUpdateResult = "img/fotos/" + fichero.getName(); } } } catch (Exception e) { ajaxUpdateResult = "ErrorException"; throw new ServletException("Parsing file upload failed.", e); } response.getWriter().print(ajaxUpdateResult); }
From source file:com.lock.unlockInfo.servlet.SubmitUnlockImg.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpResponseModel responseModel = new HttpResponseModel(); try {//from w w w .j a va 2 s. co m boolean isMultipart = ServletFileUpload.isMultipartContent(request); // ??? if (isMultipart) { Hashtable<String, String> htSubmitParam = new Hashtable<String, String>(); // ?? List<String> fileList = new ArrayList<String>();// // DiskFileItemFactory?? // ????List // list??? FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> iterator = items.iterator(); while (iterator.hasNext()) { FileItem item = iterator.next(); if (item.isFormField()) { // ? String sFieldName = item.getFieldName(); String sFieldValue = item.getString("UTF-8"); htSubmitParam.put(sFieldName, sFieldValue); } else { // ,??? String newFileName = System.currentTimeMillis() + "_" + UUID.randomUUID().toString() + ".jpg"; File filePath = new File( getServletConfig().getServletContext().getRealPath(Constants.File_Upload)); if (!filePath.exists()) { filePath.mkdirs(); } File file = new File(filePath, newFileName); if (!file.exists()) { file.createNewFile(); } //? BufferedInputStream bis = new BufferedInputStream(item.getInputStream()); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file)); byte[] b = new byte[1024]; int length = 0; while ((length = bis.read(b)) > 0) { bos.write(b, 0, length); } bos.close(); bis.close(); //?url String fileUrl = request.getRequestURL().toString(); fileUrl = fileUrl.substring(0, fileUrl.lastIndexOf("/")); //?URL fileUrl = fileUrl + Constants.File_Upload + "/" + newFileName; /**/ fileList.add(fileUrl); } } // String unlockInfoId = htSubmitParam.get("UnlockInfoId"); String imgType = htSubmitParam.get("ImgType"); String newFileUrl = fileList.get(0); UnlockInfoService unlockInfoService = (UnlockInfoService) context.getBean("unlockInfoService"); UnlockInfo unlockInfo = unlockInfoService.queryByPK(Long.valueOf(unlockInfoId)); if (imgType.equals("customerIdImg")) { unlockInfo.setCustomerIdImg(newFileUrl); } else if (imgType.equals("customerDrivingLicenseImg")) { unlockInfo.setCustomerDrivingLicenseImg(newFileUrl); } else if (imgType.equals("customerVehicleLicenseImg")) { unlockInfo.setCustomerVehicleLicenseImg(newFileUrl); } else if (imgType.equals("customerBusinessLicenseImg")) { unlockInfo.setCustomerBusinessLicenseImg(newFileUrl); } else if (imgType.equals("customerIntroductionLetterImg")) { unlockInfo.setCustomerIntroductionLetterImg(newFileUrl); } else if (imgType.equals("unlockWorkOrderImg")) { unlockInfo.setUnlockWorkOrderImg(newFileUrl); } /**/ unlockInfoService.update(unlockInfo); } } catch (Exception e) { e.printStackTrace(); responseModel.responseCode = "0"; responseModel.responseMessage = e.toString(); } /* ??? */ response.setHeader("content-type", "text/json;charset=utf-8"); response.getOutputStream().write(responseModel.toByteArray()); }
From source file:fi.vm.sade.organisaatio.resource.TempFileResource.java
@POST @Path("/") @Produces(MediaType.TEXT_PLAIN)//w ww.j av a 2s . c o m @Consumes(MediaType.MULTIPART_FORM_DATA) @Secured({ "ROLE_APP_ORGANISAATIOHALLINTA" }) public String addImage(@Context HttpServletRequest request, @Context HttpServletResponse response) { LOG.info("Adding attachment " + request.getMethod()); Map<String, String> result = null; try { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); for (FileItem item : upload.parseRequest(request)) { if (item.getName() != null) { result = storeAttachment(item); } } } else { response.setStatus(400); response.getWriter().append("Not a multipart request"); } LOG.info("Added attachment: " + result); JSONObject json = new JSONObject(result); return json.toString(); } catch (Exception e) { return "organisaatio.fileupload.error"; } }
From source file:edu.cudenver.bios.filesvc.resource.UploadResource.java
/** * Handle POST requests for file upload/*from w ww . j a va 2 s. c o m*/ * @param entity entity body information (multi-part form encoded) */ @Post public void upload(Representation entity) { if (entity != null) { if (MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) { // The Apache FileUpload project parses HTTP requests which // conform to RFC 1867, "Form-based File Upload in HTML". That // is, if an HTTP request is submitted using the POST method, // and with a content type of "multipart/form-data", then // FileUpload can parse that request, and get all uploaded files // as FileItem. // 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; try { // 3. Request is parsed by the handler which generates a // list of FileItems items = upload.parseRequest(getRequest()); // Process only the uploaded item called "fileToUpload" and // save it on disk boolean found = false; FileItem fi = null; for (final Iterator<FileItem> it = items.iterator(); it.hasNext() && !found;) { fi = (FileItem) it.next(); if (fi.getFieldName().equals(FORM_TAG_FILE)) { found = true; break; } } // Once handled, the content of the uploaded file is sent // back to the client. Representation rep = null; if (found) { // Create a new representation based on disk file. // The content is arbitrarily sent as plain text. rep = new StringRepresentation(fi.getString(), MediaType.TEXT_HTML); getResponse().setEntity(rep); getResponse().setStatus(Status.SUCCESS_OK); } else { rep = new StringRepresentation("No file data found", MediaType.TEXT_HTML); getResponse().setEntity(rep); getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST); } } catch (Exception e) { // The message of all thrown exception is sent back to // client as simple plain text getResponse().setEntity( new StringRepresentation("Upload failed: " + e.getMessage(), MediaType.TEXT_HTML)); getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST); } } } else { // POST request with no entity. getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST); } }
From source file:controllers.FrameworkController.java
private void adicionarOuEditarFramework() throws IOException { String nome, genero, paginaOficial, id, descricao, caminhoLogo; int idLinguagem = -1; genero = nome = paginaOficial = descricao = id = caminhoLogo = ""; File file;//w ww . ja v a 2 s. c o m int maxFileSize = 5000 * 1024; int maxMemSize = 5000 * 1024; ServletContext context = getServletContext(); String filePath = context.getInitParameter("file-upload"); String contentType = request.getContentType(); if ((contentType.contains("multipart/form-data"))) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(maxMemSize); factory.setRepository(new File("c:\\temp")); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxFileSize); try { List fileItems = upload.parseRequest(request); Iterator i = fileItems.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { String fileName = fi.getName(); if (fileName.lastIndexOf("\\") >= 0) { //String name = fileName.substring(fileName.lastIndexOf("\\"), fileName.lastIndexOf(".")); String name = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf(".")); file = new File(filePath + name); } else { //String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.lastIndexOf(".")); String name = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf(".")); file = new File(filePath + name); } caminhoLogo = file.getName(); fi.write(file); } else { String campo = fi.getFieldName(); String valor = fi.getString("UTF-8"); switch (campo) { case "nome": nome = valor; break; case "genero": genero = valor; break; case "pagina_oficial": paginaOficial = valor; break; case "descricao": descricao = valor; break; case "linguagem": idLinguagem = Integer.parseInt(valor); break; case "id": id = valor; break; default: break; } } } } catch (Exception ex) { System.out.println(ex); } } boolean atualizando = !id.isEmpty(); if (atualizando) { Framework framework = dao.select(Integer.parseInt(id)); framework.setDescricao(descricao); framework.setGenero(genero); framework.setIdLinguagem(idLinguagem); framework.setNome(nome); framework.setPaginaOficial(paginaOficial); if (!caminhoLogo.isEmpty()) { File imagemAntiga = new File(filePath + framework.getCaminhoLogo()); imagemAntiga.delete(); framework.setCaminhoLogo(caminhoLogo); } dao.update(framework); } else { Framework framework = new Framework(nome, descricao, genero, paginaOficial, idLinguagem, caminhoLogo); dao.insert(framework); } response.sendRedirect("frameworks.jsp"); //response.getWriter().print("<script>window.location.href='frameworks.jsp';</script>"); }
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/*from ww w .j av a 2 s .com*/ * @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:com.sketchy.server.UpgradeUploadServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { JSONServletResult jsonServletResult = new JSONServletResult(Status.SUCCESS); try {/*from w w w . j a va2 s . c o m*/ boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(FileUtils.getTempDirectory()); factory.setSizeThreshold(MAX_SIZE); ServletFileUpload servletFileUpload = new ServletFileUpload(factory); List<FileItem> files = servletFileUpload.parseRequest(request); String version = ""; for (FileItem fileItem : files) { String uploadFileName = fileItem.getName(); if (StringUtils.isNotBlank(uploadFileName)) { JarInputStream jarInputStream = null; try { // check to make sure it's a Sketchy File with a Manifest File jarInputStream = new JarInputStream(fileItem.getInputStream(), true); Manifest manifest = jarInputStream.getManifest(); if (manifest == null) { throw new Exception("Invalid Upgrade File!"); } Attributes titleAttributes = manifest.getMainAttributes(); if ((titleAttributes == null) || (!StringUtils.containsIgnoreCase( titleAttributes.getValue("Implementation-Title"), "Sketchy"))) { throw new Exception("Invalid Upgrade File!"); } version = titleAttributes.getValue("Implementation-Version"); } catch (Exception e) { throw new Exception("Invalid Upgrade File!"); } finally { IOUtils.closeQuietly(jarInputStream); } // save new .jar file as "ready" fileItem.write(new File("Sketchy.jar.ready")); jsonServletResult.put("version", version); } } } } catch (Exception e) { jsonServletResult = new JSONServletResult(Status.ERROR, e.getMessage()); } response.setContentType("text/html"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().print(jsonServletResult.toJSONString()); }
From source file:controller.UploadServlet.java
@Override 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();//w ww .j av a 2 s . com 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 + UPLOAD_DIRECTORY; // creates the directory if it does not exist File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdir(); } try { 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 filePath = uploadPath + File.separator + fileName; File storeFile = new File(filePath); // saves the file on disk item.write(storeFile); request.setAttribute("msg", UPLOAD_DIRECTORY + "/" + fileName); request.setAttribute("message", "Upload has been done successfully >>" + UPLOAD_DIRECTORY + "/" + fileName); } } } } catch (Exception ex) { request.setAttribute("message", "There was an error: " + ex.getMessage()); } // redirects client to message page getServletContext().getRequestDispatcher("/message.jsp").forward(request, response); }
From source file:influent.server.rest.ImportGraphResource.java
@Post public StringRepresentation getCapturedImage(Representation entity) throws ResourceException { if (entity == null || !MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) return null; DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1000240);//w w w . ja v a 2 s .co m RestletFileUpload upload = new RestletFileUpload(factory); try { List<FileItem> items = upload.parseRequest(getRequest()); String xmlData = new String(items.get(0).get()); JSONObject influentState = executeTask(xmlData); // hit the service to get the JSONObject if (influentState == null) { throw new ResourceException(Status.SERVER_ERROR_INTERNAL, "XML processing failed to complete for an unknown reason."); } return new StringRepresentation(influentState.toString(), MediaType.TEXT_PLAIN); } catch (Exception e) { throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Unable to create JSON object from supplied options string", e); } }
From source file:com.sketchy.server.ImageUploadServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { JSONServletResult jsonServletResult = new JSONServletResult(Status.SUCCESS); try {/*from ww w .j av a 2 s . c om*/ boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(FileUtils.getTempDirectory()); factory.setSizeThreshold(MAX_SIZE); ServletFileUpload servletFileUpload = new ServletFileUpload(factory); List<FileItem> files = servletFileUpload.parseRequest(request); for (FileItem fileItem : files) { String uploadFileName = fileItem.getName(); if (StringUtils.isNotBlank(uploadFileName)) { // Don't allow \\ in the filename, assume it's a directory separator and convert to "/" // and take the filename after the last "/" // This will fix the issue of Jetty not reading and serving files // with "\" (%5C) characters // This also fixes the issue of IE sometimes sending the whole path // (depending on the security settings) uploadFileName = StringUtils.replaceChars(uploadFileName, "\\", "/"); if (StringUtils.contains(uploadFileName, "/")) { uploadFileName = StringUtils.substringAfterLast(uploadFileName, "/"); } File uploadFile = HttpServer.getUploadFile(uploadFileName); // make sure filename is actually in the upload directory // we don't want any funny games if (!uploadFile.getParentFile().equals(HttpServer.IMAGE_UPLOAD_DIRECTORY)) { throw new RuntimeException("Can not upload File. Invalid directory!"); } // if saved ok, then need to add the data file SourceImageAttributes sourceImageAttributes = new SourceImageAttributes(); sourceImageAttributes.setImageName(uploadFileName); File pngFile = HttpServer.getUploadFile(sourceImageAttributes.getImageFilename()); if (pngFile.exists()) { throw new Exception( "Can not Upload file. File '" + uploadFileName + "' already exists!"); } File dataFile = HttpServer.getUploadFile(sourceImageAttributes.getDataFilename()); // Convert the image to a .PNG file BufferedImage image = ImageUtils.loadImage(fileItem.getInputStream()); ImageUtils.saveImage(pngFile, image); sourceImageAttributes.setWidth(image.getWidth()); sourceImageAttributes.setHeight(image.getHeight()); FileUtils.writeStringToFile(dataFile, sourceImageAttributes.toJson()); jsonServletResult.put("imageName", uploadFileName); } } } } catch (Exception e) { jsonServletResult = new JSONServletResult(Status.ERROR, e.getMessage()); } response.setContentType("text/html"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().print(jsonServletResult.toJSONString()); }