List of usage examples for org.apache.commons.fileupload FileItem write
void write(File file) throws Exception;
From source file:com.cloudbees.api.BeesClientTruProxyTest.java
@Test public void deployWarArchive() throws Exception { CloudbeesServer cloudbeesServer = new CloudbeesServer(); cloudbeesServer.startServer();// w w w. ja v a2s .c o m File local = new File("src/test/translate-puzzle-webapp-1.0.0-SNAPSHOT.war"); File uploaded = File.createTempFile("uploaded", "foo"); assertThat("We have the file to upload", local.isFile(), is(true)); assertThat("We have created the temp file to be uploaded", uploaded.isFile(), is(true)); assertThat("Precondition", local.length(), not(is(uploaded.length()))); try { BeesClientConfiguration beesClientConfiguration = new BeesClientConfiguration( "http://localhost:" + cloudbeesServer.getPort() + "/", "foo", "bar", "xml", "1.0"); BeesClient beesClient = new BeesClient(beesClientConfiguration); beesClient.setVerbose(true); MockUploadProgress mockUploadProgress = new MockUploadProgress(); beesClient.applicationDeployWar("fooId", "env", "desc", local, null, mockUploadProgress); assertNotNull(cloudbeesServer.cloudbessServlet.items); int realFilesNumber = 0; for (FileItem fileItem : cloudbeesServer.cloudbessServlet.items) { log.info("fileItem " + fileItem.getName() + ", size " + fileItem.getSize()); if (fileItem.getName() != null) { realFilesNumber++; fileItem.write(uploaded); } } assertEquals(1, realFilesNumber); assertThat("Postcondition", local.length(), is(uploaded.length())); } catch (Exception e) { throw e; } finally { cloudbeesServer.stopServer(); uploaded.delete(); } }
From source file:com.krawler.esp.handlers.genericFileUpload.java
public void uploadFile(FileItem fi, String destdir, String fileid) throws ServiceException { try {//from w w w . j a va 2 s. co m String fileName = new String(fi.getName().getBytes(), "UTF8"); File uploadFile = new File(destdir + "/" + fileName); fi.write(uploadFile); imgResizeCompany(destdir + "/" + fileName, 16, 16, destdir + "/" + fileid + "_16", false);//False is pass to indicate that image should be resize and then store. imgResizeCompany(destdir + "/" + fileName, 32, 32, destdir + "/" + fileid + "_32", false); uploadFile.delete(); } catch (Exception e) { logger.warn(e.getMessage(), e); this.ErrorMsg = "Problem occured while uploading logo"; } }
From source file:com.pdfhow.diff.UploadServlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request//from ww w.j ava2 s .com * servlet request * @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 { if (!ServletFileUpload.isMultipartContent(request)) { throw new IllegalArgumentException( "Request is not multipart, please 'multipart/form-data' enctype for your form."); } ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory()); PrintWriter writer = response.getWriter(); response.setContentType("application/json"); JSONArray json = new JSONArray(); try { List<FileItem> items = uploadHandler.parseRequest(request); for (FileItem item : items) { if (!item.isFormField()) { File file = new File(request.getServletContext().getRealPath("/") + "imgs/", item.getName()); item.write(file); JSONObject jsono = new JSONObject(); jsono.put("name", item.getName()); jsono.put("size", item.getSize()); jsono.put("url", "UploadServlet?getfile=" + item.getName()); jsono.put("thumbnail_url", "UploadServlet?getthumb=" + item.getName()); jsono.put("delete_url", "UploadServlet?delfile=" + item.getName()); jsono.put("delete_type", "GET"); json.put(jsono); System.out.println(json.toString()); } } } catch (FileUploadException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } finally { writer.write(json.toString()); writer.close(); } }
From source file:com.ci6225.marketzone.ejb.ProductBean.java
private String uploadProductImage(FileItem image, String uploadPath) throws Exception { if (CommonUtil.isSetDirectory(uploadPath)) { String fileName = new File(image.getName()).getName(); String newFileName = CommonUtil.imageNameGenerate(fileName); String filePath = uploadPath + File.separator + newFileName; File uploadedFile = new File(filePath); image.write(uploadedFile); return newFileName; }// w w w. j av a2s . c om return null; }
From source file:Index.RegisterRestaurantImagesServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from ww w . ja v a2s. com * * @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"); try (PrintWriter out = response.getWriter()) { String ubicacionArchivo = "C:\\Users\\Romina\\Documents\\NetBeansProjects\\QuickOrderWeb\\web\\images"; DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024); factory.setRepository(new File(ubicacionArchivo)); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> partes = upload.parseRequest(request); List<String> listImage = (List<String>) request.getSession().getAttribute("listImagen"); if (listImage == null) { listImage = new ArrayList<String>(); } for (FileItem item : partes) { webservice.Restaurante rest = (webservice.Restaurante) request.getSession() .getAttribute("registroUsuario"); File file = new File(ubicacionArchivo, rest.getNickname() + listImage.size() + ".jpg"); item.write(file); System.out.println("name: " + item.getName()); listImage.add(rest.getNickname() + listImage.size() + ".jpg"); } request.getSession().setAttribute("listImagen", listImage); request.getRequestDispatcher("/AltaRestauranteImagen.jsp").forward(request, response); } catch (FileUploadException ex) { System.out.println("Error al subir el archivo: " + ex.getMessage()); request.getRequestDispatcher("/AltaRestauranteImagen.jsp").forward(request, response); } catch (Exception ex) { System.out.println("Error al subir el archivo: " + ex.getMessage()); request.getRequestDispatcher("/AltaRestauranteImagen.jsp").forward(request, response); } } }
From source file:com.googlecode.example.FileUploadServlet.java
@Override @SuppressWarnings({ "unchecked" }) protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.debug("Processing request..."); if (isMultipartContent(request)) { String storageRoot = request.getSession().getServletContext().getRealPath(STORAGE_ROOT); File dirPath = new File(storageRoot); if (!dirPath.exists()) { if (dirPath.mkdirs()) { logger.debug("Storage directories created successfully."); }//from w w w .ja v a2 s . c o m } PrintWriter writer = response.getWriter(); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(UPLOAD_SIZE); factory.setRepository(dirPath); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(UPLOAD_SIZE); try { List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { if (!item.isFormField()) { File file = new File(new StringBuilder(storageRoot).append("/") .append(getName(item.getName())).toString()); logger.debug("Writing file to: {}", file.getCanonicalPath()); item.write(file); } } response.setStatus(SC_OK); } catch (Exception e) { logger.error(e.getMessage(), e); response.setStatus(SC_INTERNAL_SERVER_ERROR); } writer.flush(); } }
From source file:com.tryAndFitV1.servlet.image.DoUploadImage.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from ww w . j a v a 2 s . c om * * @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"); //process only if its multipart content String path = new File(".").getCanonicalPath(); if (ServletFileUpload.isMultipartContent(request)) { try { File file = new File(""); List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : multiparts) { if (!item.isFormField()) { String name = new File(item.getName()).getName(); System.out.println("filrpath1: " + name); file = new File(UPLOAD_DIRECTORY + File.separator + name); item.write(file); System.out.println("filrpath: " + UPLOAD_DIRECTORY + File.separator + name); } } //File uploaded successfully request.setAttribute("message1", "Fichier tlcharg avec succs"); String msg = file.getAbsolutePath(); System.err.println("fichier tlcharg : " + msg); request.setAttribute("message2", file.getAbsolutePath()); } catch (Exception ex) { request.setAttribute("message", "Echec " + ex); } } else { request.setAttribute("message", "Sorry this Servlet only handles file upload request"); } //request.getRequestDispatcher("/formBuilder.jsp").forward(request, response); }
From source file:cn.hhh.myandroidserver.response.AndServerUploadHandler.java
/** * ??SD?//from w w w . j a v a 2s . co m * * @param request {@link HttpRequest}. * @param uploadDir ? * @throws Exception ??? */ private void processFileUpload(HttpRequest request, File uploadDir) throws Exception { FileItemFactory factory = new DiskFileItemFactory(1024 * 1024, uploadDir); HttpServFileUpload fileUpload = new HttpServFileUpload(factory); // ???handlerUI fileUpload.setProgressListener(new AndWebProgressListener()); List<FileItem> fileItems = fileUpload.parseRequest(new HttpServRequestContext(request)); for (FileItem fileItem : fileItems) { if (!fileItem.isFormField()) { // ? // fileItem.getContentType() File uploadedFile = new File(uploadDir, fileItem.getName()); // ? fileItem.write(uploadedFile); } } }
From source file:com.bmth.MyServlet.RegisterServlet.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); boolean isMultipart = ServletFileUpload.isMultipartContent(request); Account account = new Account(); // process only if it is multipart content String username = "1"; if (isMultipart) { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); try {//from w ww.ja v a2s .c o m // Parse the request List<FileItem> multiparts = upload.parseRequest(request); for (FileItem item : multiparts) { if (!item.isFormField()) { String fileName = UPLOAD_DIRECTORY + File.separator + username; File file = new File(fileName); item.write(file); account.setAvatarUrl("http://localhost:8080/Avatar/" + file.getName()); } else { String fieldName = item.getFieldName(); if (fieldName.equals("firstname")) { account.setFullName(item.getString()); } if (fieldName.equals("user_name")) { username = item.getString(); account.setUsername(username); } if (fieldName.equals("nickname")) { account.setNickName(item.getString()); } if (fieldName.equals("user_password")) { account.setPassword(item.getString()); } if (fieldName.equals("user_email")) { account.setEmail(item.getString()); } if (fieldName.equals("sex")) { int gender = item.getString().equals("male") ? 1 : 0; account.setGender(gender); } if (fieldName.equals("date")) { String date = item.getString(); String[] dates = date.split("-"); Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, Integer.parseInt(dates[0])); cal.set(Calendar.MONTH, Integer.parseInt(dates[1])); cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(dates[2])); Date birtday = new Date(cal.getTimeInMillis()); account.setBirthDay(birtday); } if (fieldName.equals("address")) { account.setAddress(item.getString()); } } } } catch (Exception e) { e.printStackTrace(); } } account.setPhoneNumber("01698662215"); Register re = new Register(); boolean check = re.AddUser(account); String json; if (check) { Account account1 = re.getAccountbyUsername(username); json = "{\"userId\":" + account1.getUserId() + "}"; } else { json = "{\"userId\": 0}"; } response.getWriter().write(json); }
From source file:Control.HandleAddRestaurant.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w . ja v a 2 s .c om*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, FileUploadException, Exception { response.setContentType("text/html;charset=UTF-8"); HttpSession session = request.getSession(); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ String path = getClass().getResource("/").getPath(); String[] tempS = null; if (Paths.path == null) { File file = new File(path + "test.html"); path = file.getParent(); File file1 = new File(path + "test1.html"); path = file1.getParent(); File file2 = new File(path + "test1.html"); path = file2.getParent(); Paths.path = path; } else { path = Paths.path; } path = Paths.tempPath; Restaurant temp = new Restaurant(); String name = null; String sepName = Tools.CurrentTime(); if (ServletFileUpload.isMultipartContent(request)) { List<?> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); Iterator iter = multiparts.iterator(); int index = 0; tempS = new String[multiparts.size() - 1]; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { name = new File(item.getName()).getName(); String FilePath = path + Paths.logoPathStore + sepName + name; item.write(new File(FilePath)); } else { String test = item.getFieldName(); tempS[index++] = item.getString(); } } index = 0; temp.ID = tempS[index++]; temp.name = tempS[index++]; temp.address = tempS[index++]; temp.city = tempS[index++]; temp.state = tempS[index++]; temp.zipcode = tempS[index++]; temp.email = tempS[index++]; temp.phone = tempS[index++]; temp.monHours = tempS[index++]; temp.sunHours = tempS[index++]; temp.minPrice = Double.parseDouble(tempS[index++]); temp.fee = Double.parseDouble(tempS[index++]); temp.type = Integer.parseInt(tempS[index++]); temp.logoImage = Paths.logoPath + sepName + name; } if (Restaurant.checkExisted(temp.ID, temp.name)) { response.sendRedirect("./Admin/AddRestaurant.jsp?index=1"); } else { if (Restaurant.addNewRestaurant(temp)) { Tools.updateRestaurants(session); response.sendRedirect("./Admin/AddRestaurant.jsp?index=2"); } else { response.sendRedirect("./Admin/AddRestaurant.jsp?index=3"); } } } catch (Exception e) { response.sendRedirect("./Admin/AddRestaurant.jsp?index=0"); } }