List of usage examples for org.apache.commons.fileupload FileItem write
void write(File file) throws Exception;
From source file:admin.controller.ServletAddPersonality.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w .ja va 2s. 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 */ public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { super.processRequest(request, response); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); File file; int maxFileSize = 5000 * 1024; int maxMemSize = 5000 * 1024; try { String uploadPath = AppConstants.BRAND_IMAGES_HOME; // Verify the content type String contentType = request.getContentType(); if ((contentType.indexOf("multipart/form-data") >= 0)) { 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("/tmp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); out.println("<html>"); out.println("<head>"); out.println("<title>JSP File upload</title>"); out.println("</head>"); out.println("<body>"); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (fi.isFormField()) { // Get the uploaded file parameters field_name = fi.getFieldName(); if (field_name.equals("brandname")) { brand_name = fi.getString(); } if (field_name.equals("look")) { look_id = fi.getString(); } } else { check = brand.checkAvailability(brand_name); if (check == false) { field_name = fi.getFieldName(); file_name = fi.getName(); File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdirs(); } // int inStr = file_name.indexOf("."); // String Str = file_name.substring(0, inStr); // file_name = brand_name + "_" + Str + ".jpeg"; file_name = brand_name + "_" + file_name; boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); String filePath = uploadPath + File.separator + file_name; File storeFile = new File(filePath); fi.write(storeFile); brand.addBrands(brand_name, Integer.parseInt(look_id), file_name); response.sendRedirect(request.getContextPath() + "/admin/brandpersonality.jsp"); out.println("Uploaded Filename: " + filePath + "<br>"); } else { response.sendRedirect( request.getContextPath() + "/admin/brandpersonality.jsp?exist=exist"); } } } out.println("</body>"); out.println("</html>"); } else { out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); out.println("<p>No file uploaded</p>"); out.println("</body>"); out.println("</html>"); } } catch (Exception ex) { logger.log(Level.SEVERE, "", ex); } finally { try { out.close(); } catch (Exception e) { logger.log(Level.SEVERE, "", e); } } }
From source file:br.com.sislivros.servlets.RecuperarDadosLivro.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w. j av a 2s.c o 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 { boolean isMultipart = ServletFileUpload.isMultipartContent(request); String caminho; if (isMultipart) { try { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = (List<FileItem>) upload.parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { response.getWriter().println("Name campo:" + item.getFieldName()); response.getWriter().println("Value campo:" + item.getString()); request.setAttribute(item.getFieldName(), item.getString()); } else { //caso seja um campo do tipo file response.getWriter().println("NOT Form field"); response.getWriter().println("Name:" + item.getFieldName()); response.getWriter().println("FileNam:" + item.getName()); response.getWriter().println("Size:" + item.getSize()); response.getWriter().println("ContentType:" + item.getContentType()); response.getWriter().println( "C:\\uploads" + File.separator + new Date().getTime() + "_" + item.getName()); if (item.getName() == "" || item.getName() == null) { caminho = "img" + File.separator + "sis1.jpg"; } else { caminho = ("img" + File.separator + new Date().getTime() + "_" + item.getName()); } response.getWriter().println("Caminho: " + caminho); request.setAttribute("caminho", caminho); // File uploadedFile = new File("C:\\TomCat\\apache-tomcat-8.0.21\\webapps\\sislivros\\img" + caminho); File uploadedFile = new File( "E:\\Documentos\\NetBeansProjects\\sislivrosgit\\sisLivro\\web\\" + caminho); item.write(uploadedFile); request.setAttribute("caminho", caminho); request.getRequestDispatcher("CadastroLivroServlet").forward(request, response); } } } catch (Exception e) { response.getWriter().println("ocorreu um problema ao fazer o upload: " + e.getMessage()); } } }
From source file:com.example.web.Create_story.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); int count = 1; String storyid, storystep;/*from w w w .j av a 2 s .com*/ String fileName = ""; int f = 0; String action = ""; String first = request.getParameter("first"); String user = null; Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals("user")) user = cookie.getValue(); } } String title = request.getParameter("title"); String header = request.getParameter("header"); String text_field = request.getParameter("text_field"); String latitude = request.getParameter("lat"); String longitude = request.getParameter("lng"); storyid = (request.getParameter("storyid")); storystep = (request.getParameter("storystep")); String message = ""; int valid = 1; String query; ResultSet rs; Connection conn; String url = "jdbc:mysql://localhost:3306/"; String dbName = "tworld"; String driver = "com.mysql.jdbc.Driver"; isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { 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("/var/lib/tomcat7/webapps/www_term_project/temp/")); 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.setSizeMax(maxFileSize); try { // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); fileName = fi.getName(); String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); String[] spliting = fileName.split("\\."); // Write the file System.out.println(sizeInBytes + " " + maxFileSize); System.out.println(spliting[spliting.length - 1]); if (!fileName.equals("")) { if ((sizeInBytes < maxFileSize) && (spliting[spliting.length - 1].equals("jpg") || spliting[spliting.length - 1].equals("png") || spliting[spliting.length - 1].equals("jpeg"))) { 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: " + fileName + "<br>"); } else { valid = 0; message = "not a valid image"; } } } BufferedReader br = null; StringBuilder sb = new StringBuilder(); String line; try { br = new BufferedReader(new InputStreamReader(fi.getInputStream())); while ((line = br.readLine()) != null) { sb.append(line); } } catch (IOException e) { } finally { if (br != null) { try { br.close(); } catch (IOException e) { } } } if (f == 0) action = sb.toString(); else if (f == 1) storyid = sb.toString(); else if (f == 2) storystep = sb.toString(); else if (f == 3) title = sb.toString(); else if (f == 4) header = sb.toString(); else if (f == 5) text_field = sb.toString(); else if (f == 6) latitude = sb.toString(); else if (f == 7) longitude = sb.toString(); else if (f == 8) first = sb.toString(); f++; } } catch (Exception ex) { System.out.println("hi"); System.out.println(ex); } } if (latitude == null) latitude = ""; if (latitude.equals("") && first == null) { request.setAttribute("message", "please enter a marker"); request.setAttribute("storyid", storyid); request.setAttribute("s_page", "3"); request.setAttribute("storystep", storystep); request.getRequestDispatcher("/index.jsp").forward(request, response); } else if (valid == 1) { try { Class.forName(driver).newInstance(); conn = DriverManager.getConnection(url + dbName, "admin", "admin"); if (first != null) { if (first.equals("first_step")) { do { query = "select * from story_database where story_id='" + count + "' "; Statement st = conn.createStatement(); rs = st.executeQuery(query); count++; } while (rs.next()); int a = count - 1; request.setAttribute("storyid", a); storyid = Integer.toString(a); request.setAttribute("storystep", 2); } } query = "select * from story_database where `story_id`='" + storyid + "' && `step_num`='" + storystep + "' "; Statement st = conn.createStatement(); rs = st.executeQuery(query); if (!rs.next()) { PreparedStatement pst = (PreparedStatement) conn.prepareStatement( "insert into `tworld`.`story_database`(`story_id`, `step_num`, `content`, `latitude`, `longitude`, `title`, `header`, `max_steps`, `username`,`image_name`) values(?,?,?,?,?,?,?,?,?,?)"); pst.setInt(1, Integer.parseInt(storyid)); pst.setInt(2, Integer.parseInt(storystep)); pst.setString(3, text_field); pst.setString(4, latitude); pst.setString(5, longitude); pst.setString(6, title); pst.setString(7, header); pst.setInt(8, Integer.parseInt(storystep)); pst.setString(9, user); if (fileName.equals("")) pst.setString(10, ""); else pst.setString(10, fileName); pst.executeUpdate(); pst.close(); pst = (PreparedStatement) conn.prepareStatement( "UPDATE `tworld`.`story_database` SET `max_steps` = ? WHERE `story_id` = ?"); pst.setInt(1, Integer.parseInt(storystep)); pst.setInt(2, Integer.parseInt(storyid)); pst.executeUpdate(); pst.close(); } else { PreparedStatement pst = (PreparedStatement) conn.prepareStatement( "UPDATE `tworld`.`story_database` SET `content`=?, `latitude`=?, `longitude`=?, `title`=?, `header`=?, `max_steps`=?, `username`=? WHERE `story_id` = ? && `step_num`=?"); pst.setString(1, text_field); pst.setString(2, latitude); pst.setString(3, longitude); pst.setString(4, title); pst.setString(5, header); pst.setInt(6, Integer.parseInt(storystep)); pst.setString(7, user); pst.setInt(8, Integer.parseInt(storyid)); pst.setInt(9, Integer.parseInt(storystep)); pst.executeUpdate(); pst.close(); pst = (PreparedStatement) conn.prepareStatement( "UPDATE `tworld`.`story_database` SET `max_steps` = ? WHERE `story_id` = ?"); pst.setInt(1, Integer.parseInt(storystep)); pst.setInt(2, Integer.parseInt(storyid)); pst.executeUpdate(); pst.close(); } request.setAttribute("storyid", storyid); storystep = Integer.toString(Integer.parseInt(storystep) + 1); request.setAttribute("storystep", storystep); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) { // Logger.getLogger(MySignInServlet.class.getName()).log(Level.SEVERE, null, ex); } request.setAttribute("s_page", "3"); request.getRequestDispatcher("/index.jsp").forward(request, response); } else { request.setAttribute("storyid", storyid); request.setAttribute("message", message); request.setAttribute("storystep", storystep); request.setAttribute("s_page", "3"); request.getRequestDispatcher("/index.jsp").forward(request, response); } }
From source file:com.example.web.Update_profile.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ String fileName = ""; int f = 0; String user = null;/*from w w w .j a v a2 s. c o m*/ Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals("user")) { user = cookie.getValue(); } } } String email = request.getParameter("email"); String First_name = request.getParameter("First_name"); String Last_name = request.getParameter("Last_name"); String Phone_number_1 = request.getParameter("Phone_number_1"); String Address = request.getParameter("Address"); String message = ""; int valid = 1; String query; ResultSet rs; Connection conn; String url = "jdbc:mysql://localhost:3306/"; String dbName = "tworld"; String driver = "com.mysql.jdbc.Driver"; isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { 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("/var/lib/tomcat7/webapps/www_term_project/temp/")); 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.setSizeMax(maxFileSize); try { // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); fileName = fi.getName(); String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); String[] spliting = fileName.split("\\."); // Write the file System.out.println(sizeInBytes + " " + maxFileSize); System.out.println(spliting[spliting.length - 1]); if (!fileName.equals("")) { if ((sizeInBytes < maxFileSize) && (spliting[spliting.length - 1].equals("jpg") || spliting[spliting.length - 1].equals("png") || spliting[spliting.length - 1].equals("jpeg"))) { 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: " + fileName + "<br>"); } else { valid = 0; message = "not a valid image"; } } } BufferedReader br = null; StringBuilder sb = new StringBuilder(); String line; try { br = new BufferedReader(new InputStreamReader(fi.getInputStream())); while ((line = br.readLine()) != null) { sb.append(line); } } catch (IOException e) { } finally { if (br != null) { try { br.close(); } catch (IOException e) { } } } if (f == 0) { email = sb.toString(); } else if (f == 1) { First_name = sb.toString(); } else if (f == 2) { Last_name = sb.toString(); } else if (f == 3) { Phone_number_1 = sb.toString(); } else if (f == 4) { Address = sb.toString(); } f++; } } catch (Exception ex) { System.out.println("hi"); System.out.println(ex); } } try { Class.forName(driver).newInstance(); conn = DriverManager.getConnection(url + dbName, "admin", "admin"); if (!email.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `email`=? where `Username`=?"); pst.setString(1, email); pst.setString(2, user); pst.executeUpdate(); pst.close(); } if (!First_name.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `First_name`=? where `Username`=?"); pst.setString(1, First_name); pst.setString(2, user); pst.executeUpdate(); pst.close(); } if (!Last_name.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `Last_name`=? where `Username`=?"); pst.setString(1, Last_name); pst.setString(2, user); pst.executeUpdate(); pst.close(); } if (!Phone_number_1.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `Phone_number_1`=? where `Username`=?"); pst.setString(1, Phone_number_1); pst.setString(2, user); pst.executeUpdate(); pst.close(); } if (!Address.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `Address`=? where `Username`=?"); pst.setString(1, Address); pst.setString(2, user); pst.executeUpdate(); pst.close(); } if (!fileName.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `Fototitle`=? where `Username`=?"); pst.setString(1, fileName); pst.setString(2, user); pst.executeUpdate(); pst.close(); } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) { System.out.println("hi mom"); } request.setAttribute("s_page", "4"); request.getRequestDispatcher("/index.jsp").forward(request, response); } }
From source file:CommonServlets.EditUser.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String email = null, userName = null, job = null, address = null, password = null, img = null, role = null; BigDecimal creditLimit = new BigDecimal(0); try {//from w w w. j a va 2s .c o m // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) { //processFormField(item); String name = item.getFieldName(); String value = item.getString(); if (name.equalsIgnoreCase("email")) { email = value; } else if (name.equalsIgnoreCase("userName")) { userName = value; } else if (name.equalsIgnoreCase("creditLimit")) { DecimalFormatSymbols symbols = new DecimalFormatSymbols(); symbols.setGroupingSeparator(','); symbols.setDecimalSeparator('.'); String pattern = "#,##0.0#"; DecimalFormat decimalFormat = new DecimalFormat(pattern, symbols); decimalFormat.setParseBigDecimal(true); creditLimit = (BigDecimal) decimalFormat.parse(value); } else if (name.equalsIgnoreCase("job")) { job = value; } else if (name.equalsIgnoreCase("address")) { address = value; } else if (name.equalsIgnoreCase("password")) { password = value; } } else if (!item.isFormField() && !item.getName().equals("")) { System.out.println(new File(AddProduct.class.getClassLoader().getResource("").getPath() .replace("%20", " ") .substring(0, AddProduct.class.getClassLoader().getResource("").getPath() .replace("%20", " ").length() - 27) + "/web/Resources/users_pics/" + item.getName())); item.write(new File(AddProduct.class.getClassLoader().getResource("").getPath() .replace("%20", " ") .substring(0, AddProduct.class.getClassLoader().getResource("").getPath() .replace("%20", " ").length() - 27) + "/web/Resources/users_pics/" + item.getName())); img = item.getName(); } } User u = new User(email, userName, password, creditLimit, job, address, img, role); controlServlet.editUserDate(u); HttpSession session = request.getSession(true); session.setAttribute("done", "1"); ControlServlet c = new ControlServlet(); User myUser = c.getUser(userName); session.setAttribute("user", myUser); response.sendRedirect("UserHome.jsp"); } catch (Exception ex) { Logger.getLogger(AddProduct.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:it.univaq.servlet.Upload_rist.java
protected boolean action_upload(HttpServletRequest request) throws FileUploadException, Exception { HttpSession s = SecurityLayer.checkSession(request); //dichiaro mappe Map rist = new HashMap(); //prendo id pubblicazione dalla request if (ServletFileUpload.isMultipartContent(request)) { Map files = new HashMap(); int idpubb = Integer.parseInt(request.getParameter("id")); //La dimensione massima di ogni singolo file su system int dimensioneMassimaDelFileScrivibieSulFileSystemInByte = 10 * 1024 * 1024; // 10 MB //Dimensione massima della request int dimensioneMassimaDellaRequestInByte = 20 * 1024 * 1024; // 20 MB // Creo un factory per l'accesso al filesystem DiskFileItemFactory factory = new DiskFileItemFactory(); //Setto la dimensione massima di ogni file, opzionale factory.setSizeThreshold(dimensioneMassimaDelFileScrivibieSulFileSystemInByte); // Istanzio la classe per l'upload ServletFileUpload upload = new ServletFileUpload(factory); // Setto la dimensione massima della request upload.setSizeMax(dimensioneMassimaDellaRequestInByte); // Parso la riquest della servlet, mi viene ritornata una lista di FileItem con // tutti i field sia di tipo file che gli altri List<FileItem> items = upload.parseRequest(request); /*//from w w w. j a v a 2s . c o m * La classe usata non permette di riprendere i singoli campi per * nome quindi dovremmo scorrere la lista che ci viene ritornata con * il metodo parserequest */ //scorro per tutti i campi inviati for (int i = 0; i < items.size(); i++) { FileItem item = items.get(i); // Controllo se si tratta di un campo di input normale if (item.isFormField()) { // Prendo solo il nome e il valore String name = item.getFieldName(); String value = item.getString(); if (name.equals("isbn") || name.equals("editore") || name.equals("lingua") || name.equals("numpagine") || name.equals("datapub")) { rist.put(name, value); } } // Se si stratta invece di un file else { // Dopo aver ripreso tutti i dati disponibili name,type,size //String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); long sizeInBytes = item.getSize(); //li salvo nella mappa files.put("name", fileName); files.put("type", contentType); files.put("size", sizeInBytes); //li scrivo nel db //Database.connect(); Database.insertRecord("files", files); //Database.close(); // Posso scriverlo direttamente su filesystem if (true) { File uploadedFile = new File( getServletContext().getInitParameter("uploads.directory") + fileName); // Solo se veramente ho inviato qualcosa if (item.getSize() > 0) { item.write(uploadedFile); } } //prendo id del file se stato inserito ResultSet rs1 = Database.selectRecord("files", "name='" + files.get("name") + "'"); if (!isNull(rs1)) { while (rs1.next()) { rist.put("download", rs1.getInt("id")); } } } } rist.put("idpub", idpubb); //inserisco dati in tab ristampa Database.insertRecord("ristampa", rist); return true; } else return false; }
From source file:br.com.sislivros.servlets.RecDadosCometGroup.java
protected void processRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html;charset=UTF-8"); boolean isMultipart = ServletFileUpload.isMultipartContent(req); String caminho;/*from w w w . ja v a 2 s . c o 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()) { req.setAttribute(item.getFieldName(), item.getString()); // resp.getWriter().println("No campo file"+ this.getServletContext().getRealPath("/img")); resp.getWriter().println("Name campo: " + item.getFieldName()); resp.getWriter().println("Value campo: " + item.getString()); } else { //caso seja um campo do tipo file // resp.getWriter().println("Valor do Campo: "); // 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()); if (item.getName() == "" || item.getName() == null) { caminho = ""; } else { caminho = "img" + File.separator + new Date().getTime() + "_" + item.getName(); resp.getWriter().println("Caminho: " + caminho); // File uploadedFile = new File("C:\\TomCat\\apache-tomcat-8.0.21\\webapps\\sislivros\\" + caminho); File uploadedFile = new File( "E:\\Documentos\\NetBeansProjects\\sislivrosgit\\sisLivro\\build\\web\\" + caminho); item.write(uploadedFile); } req.setAttribute("caminho", caminho); // req.setAttribute("param", req.getParameter("comment-add")); req.getRequestDispatcher("editarGrupo").forward(req, resp); } } } catch (Exception e) { resp.getWriter().println("ocorreu um problema ao fazer o upload: " + e.getMessage()); } } }
From source file:dk.clarin.tools.create.java
public String getParmsAndFiles(List<FileItem> items, HttpServletResponse response, PrintWriter out) throws ServletException { if (!BracMat.loaded()) { response.setStatus(500);/*from ww w.j a va 2 s . co m*/ throw new ServletException("Bracmat is not loaded. Reason:" + BracMat.reason()); } String arg = "(method.POST) (DATE." + workflow.quote(date) + ")"; // bj 20120801 "(action.POST)"; try { /* * Parse the request */ Iterator<FileItem> itr = items.iterator(); while (itr.hasNext()) { logger.debug("in loop"); FileItem item = itr.next(); /* * Handle Form Fields. */ if (item.isFormField()) { logger.debug("Field Name = " + item.getFieldName() + ", String = " + item.getString()); if (item.getFieldName().equals("text")) { String LocalFileName = BracMat .Eval("storeUpload$(" + workflow.quote("text") + "." + workflow.quote(date) + ")"); int textLength = item.getString().length(); File file = new File(destinationDir, LocalFileName); item.write(file); arg = arg + " (FieldName," + workflow.quote("text") + ".Name," + workflow.quote("text") + ".ContentType," + workflow.quote("text/plain") + ".Size," + Long.toString(textLength) + ".DestinationDir," + workflow.quote( ToolsProperties.documentRoot /*+ ToolsProperties.stagingArea*//*DESTINATION_DIR_PATH*/) + ".LocalFileName," + workflow.quote(LocalFileName) + ")"; } else arg = arg + " (" + workflow.quote(item.getFieldName()) + "." + workflow.quote(item.getString()) + ")"; } else if (item.getName() != "") { //Handle Uploaded files. String LocalFileName = BracMat.Eval( "storeUpload$(" + workflow.quote(item.getName()) + "." + workflow.quote(date) + ")"); /* * Write file to the ultimate location. */ File file = new File(destinationDir, LocalFileName); item.write(file); String ContentType = item.getContentType(); logger.debug("hasNoPDFfonts ?"); logger.debug("ContentType :" + ContentType); boolean hasNoPDFfonts = false; if (ContentType.equals("application/pdf") || ContentType.equals("application/x-download") || ContentType.equals("application/octet-stream")) { logger.debug("calling PDFhasNoFonts"); hasNoPDFfonts = PDFhasNoFonts(file); logger.debug("hasNoPDFfonts " + (hasNoPDFfonts ? "true" : "false")); } arg = arg + " (FieldName," + workflow.quote(item.getFieldName()) + ".Name," + workflow.quote(item.getName()) + ".ContentType," + workflow.quote(item.getContentType()) + (hasNoPDFfonts ? " true" : "") + ".Size," + Long.toString(item.getSize()) + ".DestinationDir," + workflow.quote( ToolsProperties.documentRoot /*+ ToolsProperties.stagingArea*//*DESTINATION_DIR_PATH*/) + ".LocalFileName," + workflow.quote(LocalFileName) + ")"; } } } catch (Exception ex) { log("Error encountered while uploading file", ex); out.close(); } logger.debug("arg " + arg); return arg; }
From source file:it.infn.ct.code_rade_portlet.java
/** * This method is called when the user specifies a input file to upload * The file will be saved first into /tmp directory and then its content * stored into the corresponding String variable * Before to submit the job the String value will be stored in the * proper job inputSandbox file/* w w w .jav a2s.com*/ * * @param item * @param appInput AppInput instance storing the jobSubmission data */ void processInputFile(FileItem item, AppInput appInput) { // Determin the filename String fileName = item.getName(); if (!fileName.equals("")) { // Determine the fieldName String fieldName = item.getFieldName(); // Create a filename for the uploaded file String theNewFileName = "/tmp/" + appInput.timestamp + "_" + appInput.username + "_" + fileName; File uploadedFile = new File(theNewFileName); _log.info("Uploading file: '" + fileName + "' into '" + theNewFileName + "'"); try { item.write(uploadedFile); } catch (Exception e) { _log.error("Caught exception while uploading file: 'file_inputFile'"); } // File content has to be inserted into a String variables: // inputFileName -> inputFileText try { if (fieldName.equals("file_inputFile")) appInput.inputFileText = updateString(theNewFileName); // Other params can be added as below ... //else if(fieldName.equals("...")) // ...=updateString(theNewFileName); else { // Never happens } } catch (Exception e) { _log.error("Caught exception while processing strings: '" + e.toString() + "'"); } } // if }
From source file:com.silverpeas.jobStartPagePeas.control.JobStartPagePeasSessionController.java
private void processSpaceCSS(List<FileItem> items, String path) throws Exception { FileItem file = FileUploadUtil.getFile(items, "css"); if (file != null && StringUtil.isDefined(file.getName())) { // Remove previous file File css = new File(path, SilverpeasLook.SPACE_CSS + ".css"); if (css != null && css.exists()) { css.delete();//from ww w . j a va2s . c o m } file.write(css); } }