List of usage examples for org.apache.commons.fileupload FileItem write
void write(File file) throws Exception;
From source file:eu.wisebed.wiseui.server.rpc.ImageUploadServiceImpl.java
/** * Override executeAction to save the received files in a custom place * and delete these items from session// w ww .ja v a 2 s.c o m */ @Override public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException { String response = ""; int cont = 0; for (FileItem item : sessionFiles) { if (false == item.isFormField()) { cont++; try { // Save a temporary file in the default system temp directory File uploadedFile = File.createTempFile("upload-", ".bin"); // write item to a file item.write(uploadedFile); // open and read content from file stream FileInputStream in = new FileInputStream(uploadedFile); byte fileContent[] = new byte[(int) uploadedFile.length()]; in.read(fileContent); // store content in persistance BinaryImage image = new BinaryImage(); image.setFileName(item.getName()); image.setFileSize(item.getSize()); image.setContent(fileContent); image.setContentType(item.getContentType()); LOGGER.info("Storing image: [Filename-> " + item.getName() + " ]"); persistenceService.storeBinaryImage(image); // Compose an xml message with the full file information // which can be parsed in client side response += "<file-" + cont + "-field>" + item.getFieldName() + "</file-" + cont + "-field>\n"; response += "<file-" + cont + "-name>" + item.getName() + "</file-" + cont + "-name>\n"; response += "<file-" + cont + "-size>" + item.getSize() + "</file-" + cont + "-size>\n"; response += "<file-" + cont + "-type>" + item.getContentType() + "</file-" + cont + "-type>\n"; } catch (Exception e) { throw new UploadActionException(e); } } } // Remove files from session because we have a copy of them removeSessionFileItems(request); // set the count of files response += "<file-count>" + cont + "</file-count>\n"; // Send information of the received files to the client return "<response>\n" + response + "</response>\n"; }
From source file:guru.bubl.service.resources.vertex.VertexImageResource.java
@POST @Consumes(MediaType.MULTIPART_FORM_DATA) @GraphTransactional/*www. j a v a2s. co m*/ @Produces(MediaType.APPLICATION_JSON) @Path("/") public Response add(@Context HttpServletRequest request) { Set<Image> uploadedImages = new HashSet<>(); if (ServletFileUpload.isMultipartContent(request)) { final FileItemFactory factory = new DiskFileItemFactory(); final ServletFileUpload fileUpload = new ServletFileUpload(factory); try { /* * parseRequest returns a list of FileItem * but in old (pre-java5) style */ final List items = fileUpload.parseRequest(request); if (items != null) { final Iterator iter = items.iterator(); while (iter.hasNext()) { final FileItem item = (FileItem) iter.next(); String imageId = UUID.randomUUID().toString(); final File savedFile = new File(IMAGES_FOLDER_PATH + File.separator + imageId); System.out.println("Saving the file: " + savedFile.getName()); item.write(savedFile); saveBigImage(savedFile); String imageBaseUrl = request.getRequestURI() + "/" + imageId + "/"; String base64ForSmallImage = Base64.encodeBase64String(resizedSmallImage(savedFile)); uploadedImages.add(Image.withBase64ForSmallAndUriForBigger(base64ForSmallImage, URI.create(imageBaseUrl + "big"))); } } vertex.addImages(uploadedImages); return Response.ok().entity(ImageJson.toJsonArray(uploadedImages)).build(); } catch (Exception exception) { exception.printStackTrace(); throw new WebApplicationException(Response.Status.BAD_REQUEST); } } throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); }
From source file:com.certus.actions.uploadSliderImageAction.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String path = getServletContext().getRealPath("img/slider").replace("build/", ""); boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try {/*from ww w . ja v a2s .c om*/ List<FileItem> multiparts = upload.parseRequest(request); StringBuilder sb = null; for (FileItem item : multiparts) { if (!item.isFormField()) { double randomA = Math.random() * 1000000000; int randA = (int) randomA; String name = new File(item.getName()).getName(); sb = new StringBuilder(name); sb.replace(0, name.length() - 4, "slider-" + randA); item.write(new File(path + File.separator + sb)); } } String pathTo = path + File.separator + sb; response.getWriter().write(pathTo.substring(pathTo.lastIndexOf("img"))); } catch (Exception e) { e.printStackTrace(); } } }
From source file:fll.web.UploadSpreadsheet.java
protected void processRequest(final HttpServletRequest request, final HttpServletResponse response, final ServletContext application, final HttpSession session) throws IOException, ServletException { final StringBuilder message = new StringBuilder(); String nextPage;//from ww w .j a va 2 s. c o m try { UploadProcessor.processUpload(request); final String uploadRedirect = (String) request.getAttribute("uploadRedirect"); if (null == uploadRedirect) { throw new RuntimeException( "Missing parameter 'uploadRedirect' params: " + request.getParameterMap()); } session.setAttribute("uploadRedirect", uploadRedirect); final FileItem fileItem = (FileItem) request.getAttribute("file"); final String extension = Utilities.determineExtension(fileItem.getName()); final File file = File.createTempFile("fll", extension); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Wrote data to: " + file.getAbsolutePath()); } fileItem.write(file); session.setAttribute(SPREADSHEET_FILE_KEY, file.getAbsolutePath()); if (ExcelCellReader.isExcelFile(file)) { final List<String> sheetNames = ExcelCellReader.getAllSheetNames(file); if (sheetNames.size() > 1) { session.setAttribute("sheetNames", sheetNames); nextPage = "promptForSheetName.jsp"; } else { session.setAttribute(SHEET_NAME_KEY, sheetNames.get(0)); nextPage = uploadRedirect; } } else { nextPage = uploadRedirect; } } catch (final FileUploadException e) { message.append("<p class='error'>Error processing team data upload: " + e.getMessage() + "</p>"); LOGGER.error(e, e); throw new RuntimeException("Error processing team data upload", e); } catch (final Exception e) { message.append("<p class='error'>Error saving team data into the database: " + e.getMessage() + "</p>"); LOGGER.error(e, e); throw new RuntimeException("Error saving team data into the database", e); } session.setAttribute("message", message.toString()); response.sendRedirect(response.encodeRedirectURL(nextPage)); }
From source file:com.pamarin.servlet.uploadfile.UploadFileServet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { LOG.log(Level.INFO, "uploaded"); try {//from ww w . j a va 2 s. c om if (!ServletFileUpload.isMultipartContent(request)) { return; } LOG.log(Level.INFO, "is multipart"); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(maxMemSize); factory.setRepository(new File("c:\\temp")); // ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxFileSize); List<FileItem> fileItems = upload.parseRequest(request); Iterator<FileItem> iterator = fileItems.iterator(); LOG.log(Level.INFO, "file size --> {0}", fileItems.size()); while (iterator.hasNext()) { FileItem item = iterator.next(); //if (!item.isFormField()) { LOG.log(Level.INFO, "content type --> {0}", item.getContentType()); LOG.log(Level.INFO, "name --> {0}", item.getName()); LOG.log(Level.INFO, "field name --> {0}", item.getFieldName()); LOG.log(Level.INFO, "string --> {0}", item.getString()); item.write(new File("c:\\temp", UUID.randomUUID().toString() + ".png")); //} } } catch (FileUploadException ex) { LOG.log(Level.WARNING, ex.getMessage()); } catch (Exception ex) { LOG.log(Level.WARNING, ex.getMessage()); } }
From source file:it.eng.spagobi.engines.worksheet.services.designer.UploadWorksheetImageAction.java
private void saveFile(FileItem uploaded) { logger.debug("IN"); try {/*from ww w.j a v a 2 s . co m*/ String fileName = SpagoBIUtilities.getRelativeFileNames(uploaded.getName()); File imagesDir = QbeEngineConfig.getInstance().getWorksheetImagesDir(); File saveTo = new File(imagesDir, fileName); uploaded.write(saveTo); } catch (Throwable t) { throw new SpagoBIEngineServiceException(getActionName(), "Error while saving file into server", t); } finally { logger.debug("OUT"); } }
From source file:controladoresAdministrador.ControladorCargarInicial.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w .j a v a2s .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, FileUploadException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); DiskFileItemFactory ff = new DiskFileItemFactory(); ServletFileUpload sfu = new ServletFileUpload(ff); List items = null; File archivo = null; try { items = sfu.parseRequest(request); } catch (FileUploadException ex) { out.print(ex.getMessage()); } String nombre = ""; FileItem item = null; for (int i = 0; i < items.size(); i++) { item = (FileItem) items.get(i); if (!item.isFormField()) { nombre = item.getName(); archivo = new File(this.getServletContext().getRealPath("/archivos/") + "/" + item.getName()); try { item.write(archivo); } catch (Exception ex) { out.print(ex.getMessage()); } } } CargaInicial carga = new CargaInicial(); String ubicacion = archivo.toString(); int cargado = carga.cargar(ubicacion); if (cargado == 1) { response.sendRedirect( "pages/indexadmin.jsp?msg=<strong><i class='glyphicon glyphicon-exclamation-sign'></i> No se encontro el archivo!</strong> Por favor intentelo de nuevo.&tipoAlert=warning"); } else { response.sendRedirect( "pages/indexadmin.jsp?msg=<strong>Carga inicial exitosa! <i class='glyphicon glyphicon-ok'></i></strong>&tipoAlert=success"); } }
From source file:com.cwctravel.jenkinsci.plugins.htmlresource.HTMLResourceManagement.java
void saveHTMLResource(FileItem fileItem, String fileName) throws Exception, IOException { File rootDir = getWebJARDirectory(); final File f = new File(rootDir, fileName); fileItem.write(f); if (validateWebJAR(f)) { HTMLResource resource = new HTMLResource(fileName, fileName, -1, null); HTMLResourceConfiguration config = getConfiguration(); config.addOrReplace(resource);// ww w . jav a 2s .c o m config.save(); } }
From source file:controller.MencatatPembayaran.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Pembayaran p = new Pembayaran(); DatabaseManager db = new DatabaseManager(); //Menyimpan file ke dalam sistem if (ServletFileUpload.isMultipartContent(request)) { try {//from w ww. j a v a 2 s . co m List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : multiparts) { if (!item.isFormField()) { String fileNameSource = new File(item.getName()).getName();//Mengambil nama sumber file String name = "DataPembayaran_" + timeStamp + ".csv"; //Membuat nama file untuk disimpan item.write(new File(UPLOAD_DIRECTORY + File.separator + name)); if (fileNameSource.isEmpty()) { //Mengecek apakah ada file yang diupload throw new Exception("Tidak ada file yang diupload"); } if (!fileNameSource.contains(".csv")) { //Mengecek apakah file bertipe .csv throw new Exception("Format file salah"); } } } } catch (Exception ex) { returnError(request, response, ex); } } else { returnError(request, response, new Exception("Error mengupload file")); } //Membaca file dari dalam sistem String csvFile = UPLOAD_DIRECTORY + "DataPembayaran_" + timeStamp + ".csv"; BufferedReader br = null; String line = ""; String cvsSplitBy = ","; try { br = new BufferedReader(new FileReader(csvFile)); int counter = 1; while ((line = br.readLine()) != null) { // use comma as separator String[] dataSet = line.split(cvsSplitBy); p.setID(timeStamp2 + "_" + counter); p.setWaktuPembayaran(dataSet[0]); p.setNoRekening(dataSet[1]); p.setJumlahPembayaran(Double.parseDouble(dataSet[2])); p.setNis(dataSet[3].substring(0, 5)); // Mengubah berita acara menjadi NIS p.setJenisPembayaran(dataSet[3].substring(6)); // Mengubah berita acara menjadi jenis pembayaran db.simpanPembayaran(p); counter++; } this.tampil(request, response, "Data Tersimpan"); } catch (FileNotFoundException e) { returnError(request, response, e); } catch (IOException e) { returnError(request, response, e); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } }
From source file:hu.ptemik.gallery.servlets.UploadServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(false); User user = (User) session.getAttribute("user"); String uploadFolder = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY; if (ServletFileUpload.isMultipartContent(request) && user != null) { try {//from w ww .j av a 2 s .c om List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); Picture pic = new Picture(); File uploadedFile = null; for (FileItem item : multiparts) { if (!item.isFormField()) { String fileName = new File(item.getName()).getName(); String filePath = uploadFolder + File.separator + fileName; String relativePath = UPLOAD_DIRECTORY + "/" + fileName; uploadedFile = new File(filePath); item.write(uploadedFile); pic.setUrl(relativePath); } else { if (item.getFieldName().equals("title")) { pic.setTitle(item.getString()); } else if (item.getFieldName().equals("description")) { pic.setDescription(item.getString()); } } } if (Controller.newPicture(pic, user)) { request.setAttribute("successMessage", "A fjl feltltse sikerlt!"); } else { FileUtils.deleteQuietly(uploadedFile); throw new Exception(); } } catch (FileNotFoundException ex) { request.setAttribute("errorMessage", "Hinyzik a fjl!"); } catch (Exception ex) { request.setAttribute("errorMessage", "Hiba a fjl feltltse sorn!"); } } else { request.setAttribute("errorMessage", "Form hiba"); } request.getRequestDispatcher("upload.jsp").forward(request, response); }