List of usage examples for org.apache.commons.fileupload FileItem write
void write(File file) throws Exception;
From source file:com.afis.jx.ckfinder.connector.handlers.command.FileUploadCommand.java
/** * saves temporary file in the correct file path. * * @param path path to save file//from w ww.j a va2s.c o m * @param item file upload item * @return result of saving, true if saved correctly * @throws Exception when error occurs. */ private boolean saveTemporaryFile(final String path, final FileItem item) throws Exception { File file = new File(path, this.newFileName); AfterFileUploadEventArgs args = new AfterFileUploadEventArgs(); args.setCurrentFolder(this.currentFolder); args.setFile(file); args.setFileContent(item.get()); if (!ImageUtils.isImage(file)) { item.write(file); if (configuration.getEvents() != null) { configuration.getEvents().run(EventTypes.AfterFileUpload, args, configuration); } return true; } else if (ImageUtils.checkImageSize(item.getInputStream(), this.configuration) || configuration.checkSizeAfterScaling()) { ImageUtils.createTmpThumb(item.getInputStream(), file, getFileItemName(item), this.configuration); if (!configuration.checkSizeAfterScaling() || FileUtils.checkFileSize(configuration.getTypes().get(this.type), file.length())) { if (configuration.getEvents() != null) { configuration.getEvents().run(EventTypes.AfterFileUpload, args, configuration); } return true; } else { file.delete(); this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_TOO_BIG; return false; } } else { this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_TOO_BIG; return false; } }
From source file:com.stratelia.webactiv.servlets.FileUploader.java
private void processVersion(String documentId, int versionType, String comment, FileItem file, String userId, String language) throws Exception { VersioningUtil versioningUtil = new VersioningUtil(); DocumentVersion documentVersion = versioningUtil .getLastVersion(new DocumentPK(Integer.parseInt(documentId))); String componentId = documentVersion.getInstanceId(); String logicalName = documentVersion.getLogicalName(); String suffix = FileRepositoryManager.getFileExtension(logicalName); String newPhysicalName = new Long(new Date().getTime()).toString() + "." + suffix; String newVersionFile = FileRepositoryManager.getAbsolutePath(componentId) + DocumentVersion.CONTEXT_VERSIONING + newPhysicalName; File uploadFile = new File(newVersionFile); file.write(uploadFile); versioningUtil.checkinFile(documentId, versionType, comment, userId, newPhysicalName); }
From source file:game.com.HandleUploadGameGalleryServlet.java
private void handle(HttpServletRequest request, AjaxResponseEntity responseObject) throws Exception { boolean isMultipart; String filePath;//from ww w . j av a 2 s . c o m int maxFileSize = 4 * 1024 * 1024; int maxMemSize = 4 * 1024 * 1024; File file; 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); Map<String, List<FileItem>> postData = upload.parseParameterMap(request); String id = postData.get("id").get(0).getString(); if (StringUtils.isBlank(id)) { logger.info("id= " + id); } File folder = new File(AppConfig.OPENSHIFT_DATA_DIR + "/gallery/" + id); if (!folder.exists()) { folder.mkdir(); } try { // Parse the request to get file items. List<FileItem> fileItems = postData.get("imagegallery"); // Process the uploaded file items SimpleDateFormat dateFormat = new SimpleDateFormat("MMddhhmmSSS"); for (FileItem fi : fileItems) { if (!fi.isFormField()) { // Get the uploaded file parameters // String fieldName = fi.getFieldName(); // String fileName = fi.getName(); // String contentType = fi.getContentType(); // boolean isInMemory = fi.isInMemory(); // long sizeInBytes = fi.getSize(); // Write the file String filename = dateFormat.format(new Date()); file = new File(AppConfig.OPENSHIFT_DATA_DIR + "/gallery/" + id + "/" + filename + ".png"); fi.write(file); } else { logger.info("isFormField " + fi.getFieldName()); } } List<String> gallery = getGalleryImage(id); responseObject.data = new Gson().toJson(gallery); responseObject.returnCode = 1; responseObject.returnMessage = "success"; } catch (Exception ex) { logger.error(ex.getMessage(), ex); } }
From source file:UploadImageEdit.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from www . ja v a 2 s .co 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, IOException_Exception { // Check that we have a file upload request PrintWriter writer = response.getWriter(); String productName = ""; String description = ""; String price = ""; String pictureName = ""; String productId = ""; Cookie cookie = null; Cookie[] cookies = null; String selectedCookie = ""; // Get an array of Cookies associated with this domain cookies = request.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { cookie = cookies[i]; if (cookie.getName().equals("JuraganDiskon")) { selectedCookie = cookie.getValue(); } } } else { writer.println("<h2>No cookies founds</h2>"); } if (!ServletFileUpload.isMultipartContent(request)) { // if not, we stop here 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 = new File(new File(getServletContext().getRealPath("")).getParent()).getParent() + "/web/" + 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 int k = 0; for (FileItem item : formItems) { // processes only fields that are not form fields if (!item.isFormField()) { k++; writer.println("if = " + k); String fileName = new File(item.getName()).getName(); pictureName = fileName; String filePath = uploadPath + File.separator + fileName; File storeFile = new File(filePath); // saves the file on disk item.write(storeFile); request.setAttribute("message", "Upload has been done successfully!"); writer.println("pictureName = " + pictureName); } else { k++; writer.println("else = " + k); // Get the field name String fieldName = item.getName(); // Get the field value String value = item.getString(); if (k == 0) { } else if (k == 1) { productId = value.trim(); writer.println("productId = " + productId); } else if (k == 2) { productName = value; writer.println("productName = " + productName); } else if (k == 3) { description = value; writer.println("description = " + description); } else if (k == 4) { price = value; writer.println("price = " + price); } } } } } catch (Exception ex) { request.setAttribute("message", "There was an error: " + ex.getMessage()); } String update = editTheProduct(Integer.valueOf(productId), productName, price, description, pictureName, selectedCookie); writer.println(update); //redirects client to message page getServletContext().getRequestDispatcher("/yourProduct.jsp").forward(request, response); }
From source file:adminShop.registraProducto.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*www. j a v a2 s .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 { String message = "Error"; boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items; HashMap hm = new HashMap(); ArrayList<Imagen> imgs = new ArrayList<>(); Producto prod = new Producto(); Imagen img = null; try { items = upload.parseRequest(request); Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) { String name = item.getFieldName(); String value = item.getString(); hm.put(name, value); } else { img = new Imagen(); String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeBytes = item.getSize(); File file = new File("/home/gama/Escritorio/adoo/" + fileName + ".jpg"); item.write(file); Path path = Paths.get("/home/gama/Escritorio/adoo/" + fileName + ".jpg"); byte[] data = Files.readAllBytes(path); byte[] encode = org.apache.commons.codec.binary.Base64.encodeBase64(data); img.setUrl(new javax.sql.rowset.serial.SerialBlob(encode)); imgs.add(img); //file.delete(); } } prod.setNombre((String) hm.get("nombre")); prod.setProdNum((String) hm.get("prodNum")); prod.setDesc((String) hm.get("desc")); prod.setIva(Double.parseDouble((String) hm.get("iva"))); prod.setPrecio(Double.parseDouble((String) hm.get("precio"))); prod.setPiezas(Integer.parseInt((String) hm.get("piezas"))); prod.setEstatus("A"); prod.setImagenes(imgs); ProductoDAO prodDAO = new ProductoDAO(); if (prodDAO.registraProducto(prod)) { message = "Exito"; } } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } response.sendRedirect("index.jsp"); }
From source file:com.linkedin.pinot.controller.api.restlet.resources.PinotSegmentUploadRestletResource.java
@Override @Post// w w w. ja v a 2 s. c o m public Representation post(Representation entity) { Representation rep = null; File tmpSegmentDir = null; File dataFile = null; try { // 0/ Get upload type, if it's uri, then download it, otherwise, get the tar from the request. Series headers = (Series) getRequestAttributes().get(RESTLET_HTTP_HEADERS); String uploadTypeStr = headers.getFirstValue(FileUploadUtils.UPLOAD_TYPE); FileUploadType uploadType = null; try { uploadType = (uploadTypeStr == null) ? FileUploadType.getDefaultUploadType() : FileUploadType.valueOf(uploadTypeStr); } catch (Exception e) { uploadType = FileUploadType.getDefaultUploadType(); } String downloadURI = null; boolean found = false; switch (uploadType) { case URI: case JSON: // Download segment from the given Uri try { downloadURI = getDownloadUri(uploadType, headers, entity); } catch (Exception e) { String errorMsg = String.format( "Failed to get download Uri for upload file type: %s, with error %s", uploadType, e.getMessage()); LOGGER.warn(errorMsg); JSONObject errorMsgInJson = getErrorMsgInJson(errorMsg); ControllerRestApplication.getControllerMetrics() .addMeteredGlobalValue(ControllerMeter.CONTROLLER_SEGMENT_UPLOAD_ERROR, 1L); setStatus(Status.CLIENT_ERROR_BAD_REQUEST); return new StringRepresentation(errorMsgInJson.toJSONString(), MediaType.APPLICATION_JSON); } SegmentFetcher segmentFetcher = null; // Get segmentFetcher based on uri parsed from download uri try { segmentFetcher = SegmentFetcherFactory.getSegmentFetcherBasedOnURI(downloadURI); } catch (Exception e) { String errorMsg = String.format("Failed to get SegmentFetcher from download Uri: %s", downloadURI); LOGGER.warn(errorMsg); JSONObject errorMsgInJson = getErrorMsgInJson(errorMsg); ControllerRestApplication.getControllerMetrics() .addMeteredGlobalValue(ControllerMeter.CONTROLLER_SEGMENT_UPLOAD_ERROR, 1L); setStatus(Status.SERVER_ERROR_INTERNAL); return new StringRepresentation(errorMsgInJson.toJSONString(), MediaType.APPLICATION_JSON); } // Download segment tar to local. dataFile = new File(tempDir, "tmp-" + System.nanoTime()); try { segmentFetcher.fetchSegmentToLocal(downloadURI, dataFile); } catch (Exception e) { String errorMsg = String.format("Failed to fetch segment tar from download Uri: %s to %s", downloadURI, dataFile.toString()); LOGGER.warn(errorMsg); JSONObject errorMsgInJson = getErrorMsgInJson(errorMsg); ControllerRestApplication.getControllerMetrics() .addMeteredGlobalValue(ControllerMeter.CONTROLLER_SEGMENT_UPLOAD_ERROR, 1L); setStatus(Status.SERVER_ERROR_INTERNAL); return new StringRepresentation(errorMsgInJson.toJSONString(), MediaType.APPLICATION_JSON); } if (dataFile.exists() && dataFile.length() > 0) { found = true; } break; case TAR: default: // 1/ Create a factory for disk-based file items final DiskFileItemFactory factory = new DiskFileItemFactory(); // 2/ Create a new file upload handler based on the Restlet // FileUpload extension that will parse Restlet requests and // generates FileItems. final RestletFileUpload upload = new RestletFileUpload(factory); final List<FileItem> items; // 3/ Request is parsed by the handler which generates a // list of FileItems items = upload.parseRequest(getRequest()); for (final Iterator<FileItem> it = items.iterator(); it.hasNext() && !found;) { final FileItem fi = it.next(); if (fi.getFieldName() != null) { found = true; dataFile = new File(tempDir, fi.getFieldName()); fi.write(dataFile); } } } // Once handled, the content of the uploaded file is sent // back to the client. if (found) { // Create a new representation based on disk file. // The content is arbitrarily sent as plain text. rep = new StringRepresentation(dataFile + " sucessfully uploaded", MediaType.TEXT_PLAIN); tmpSegmentDir = new File(tempUntarredPath, dataFile.getName() + "-" + _controllerConf.getControllerHost() + "_" + _controllerConf.getControllerPort() + "-" + System.currentTimeMillis()); LOGGER.info("Untar segment to temp dir: " + tmpSegmentDir); if (tmpSegmentDir.exists()) { FileUtils.deleteDirectory(tmpSegmentDir); } if (!tmpSegmentDir.exists()) { tmpSegmentDir.mkdirs(); } // While there is TarGzCompressionUtils.unTarOneFile, we use unTar here to unpack all files // in the segment in order to ensure the segment is not corrupted TarGzCompressionUtils.unTar(dataFile, tmpSegmentDir); File segmentFile = tmpSegmentDir.listFiles()[0]; String clientIpAddress = getClientInfo().getAddress(); String clientAddress = InetAddress.getByName(clientIpAddress).getHostName(); LOGGER.info("Processing upload request for segment '{}' from client '{}'", segmentFile.getName(), clientAddress); return uploadSegment(segmentFile, dataFile, downloadURI); } else { // Some problem occurs, sent back a simple line of text. String errorMsg = "No file was uploaded"; LOGGER.warn(errorMsg); JSONObject errorMsgInJson = getErrorMsgInJson(errorMsg); rep = new StringRepresentation(errorMsgInJson.toJSONString(), MediaType.APPLICATION_JSON); ControllerRestApplication.getControllerMetrics() .addMeteredGlobalValue(ControllerMeter.CONTROLLER_SEGMENT_UPLOAD_ERROR, 1L); setStatus(Status.SERVER_ERROR_INTERNAL); } } catch (final Exception e) { rep = exceptionToStringRepresentation(e); LOGGER.error("Caught exception in file upload", e); ControllerRestApplication.getControllerMetrics() .addMeteredGlobalValue(ControllerMeter.CONTROLLER_SEGMENT_UPLOAD_ERROR, 1L); setStatus(Status.SERVER_ERROR_INTERNAL); } finally { if ((tmpSegmentDir != null) && tmpSegmentDir.exists()) { try { FileUtils.deleteDirectory(tmpSegmentDir); } catch (final IOException e) { LOGGER.error("Caught exception in file upload", e); ControllerRestApplication.getControllerMetrics() .addMeteredGlobalValue(ControllerMeter.CONTROLLER_SEGMENT_UPLOAD_ERROR, 1L); setStatus(Status.SERVER_ERROR_INTERNAL); } } if ((dataFile != null) && dataFile.exists()) { FileUtils.deleteQuietly(dataFile); } } return rep; }
From source file:it.unisa.tirocinio.servlet.studentUploadFiles.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// ww w . j a va2 s. 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 { response.setContentType("text/html;charset=UTF-8"); response.setHeader("Access-Control-Allow-Origin", "*"); PrintWriter out = response.getWriter(); HttpSession aSession = request.getSession(); try { Person pers = (Person) aSession.getAttribute("person"); String primaryKey = pers.getAccount().getEmail(); PersonManager aPerson = PersonManager.getInstance(); Person person = aPerson.getStudent(primaryKey); ConcreteStudentInformation aStudentInformation = ConcreteStudentInformation.getInstance(); out = response.getWriter(); String studentSubfolderPath = filePath + "/" + reverseSerialNumber(person.getMatricula()); File subfolderFile = new File(studentSubfolderPath); if (!subfolderFile.exists()) { subfolderFile.mkdir(); } isMultipart = ServletFileUpload.isMultipartContent(request); String serialNumber = null; DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List fileItems = upload.parseRequest(request); Iterator i = fileItems.iterator(); File fileToStore = null; String CVPath = "", ATPath = ""; while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); String fileName = fi.getName(); if (fieldName.equals("cv")) { fileToStore = new File(studentSubfolderPath + "/" + "CV.pdf"); CVPath = fileToStore.getAbsolutePath(); } else if (fieldName.equals("doc")) { fileToStore = new File(studentSubfolderPath + "/" + "ES.pdf"); ATPath = fileToStore.getAbsolutePath(); } fi.write(fileToStore); // out.println("Uploaded Filename: " + fieldName + "<br>"); } else { //out.println("It's not formfield"); //out.println(fi.getString()); } } if (aStudentInformation.startTrainingRequest(person.getSsn(), CVPath, ATPath)) { message.setMessage("status", 1); } else { message.setMessage("status", 0); } aSession.setAttribute("message", message); response.sendRedirect(request.getContextPath() + "/tirocinio/studente/tprichiestatirocinio.jsp"); //RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/tirocinio/studente/tprichiestatirocinio.jsp"); //dispatcher.forward(request,response); } catch (Exception ex) { Logger.getLogger(studentUploadFiles.class.getName()).log(Level.SEVERE, null, ex); message.setMessage("status", -1); aSession.setAttribute("message", message); } finally { out.close(); } }
From source file:de.knurt.fam.core.model.config.FileUploadController.java
public ModelAndView getModelAndView() { ModelAndView result = null;//from ww w .j av a2 s . c o m if (tr.getFilename().equalsIgnoreCase("get") && tr.getRequest().getMethod().equalsIgnoreCase("GET") && tr.getSuffix().equalsIgnoreCase("html")) { // initial call for the fileupload page (<iframe // src="get-fileupload.html" ...) tr.setTemplateFile("page_fileupload.html"); result = TemplateConfig.me().getResourceController().handleGetRequests(tr, response, tr.getRequest()); } else if (tr.getFilename().equalsIgnoreCase("put") && tr.getRequest().getMethod().equalsIgnoreCase("GET") && tr.getSuffix().equalsIgnoreCase("json")) { // requesting existing files JSONArray json = new JSONArray(); File[] existings = this.getExistingFileNames(); for (File existing : existings) { json.put(this.getJSONObject(existing)); } this.write(json); } else if (tr.getFilename().equalsIgnoreCase("delete") && (tr.getRequest().getMethod().equalsIgnoreCase("POST") || tr.getRequest().getMethod().equalsIgnoreCase("DELETE")) && tr.getSuffix().equalsIgnoreCase("json")) { // delete boolean succ = false; File fileToDelete = this.getExistingFile(tr.getRequest().getParameter("file")); if (fileToDelete != null) { succ = fileToDelete.delete(); } this.write(succ ? "true" : "false"); } else if (tr.getFilename().equalsIgnoreCase("download") && tr.getRequest().getMethod().equalsIgnoreCase("GET") && tr.getSuffix().equalsIgnoreCase("json")) { File fileToDownload = this.getExistingFile(tr.getRequest().getParameter("file")); if (fileToDownload != null) { // force "save as" in browser response.setHeader("Content-Disposition", "attachment; filename=" + fileToDownload.getName()); // it is a pdf response.setContentType(mftm.getContentType(fileToDownload)); ServletOutputStream outputStream = null; FileInputStream inputStream = null; try { outputStream = response.getOutputStream(); inputStream = new FileInputStream(fileToDownload); int nob = IOUtils.copy(inputStream, outputStream); if (nob < 1) FamLog.error("fail to download: " + fileToDownload.getAbsolutePath(), 201204181310l); } catch (IOException e) { FamLog.exception(e, 201204181302l); } finally { IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); } } } else if (tr.getFilename().equalsIgnoreCase("put") && tr.getRequest().getMethod().equalsIgnoreCase("POST") && tr.getSuffix().equalsIgnoreCase("json") && ServletFileUpload.isMultipartContent(tr.getRequest())) { // insert JSONObject json_result = new JSONObject(); // Parse the request try { // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(tr.getRequest()); this.setError(items); if (this.error == null) { // Process the uploaded items for (FileItem item : items) { if (!item.isFormField()) { File uploadedFile = null; File upload_dir = this.uploadDir; if (upload_dir != null) { uploadedFile = new File(upload_dir.getAbsolutePath() + File.separator + this.getNewFilename(item.getName())); } try { item.write(uploadedFile); json_result = this.getJSONObject(uploadedFile); } catch (Exception e) { FamLog.exception(e, 201204170945l); json_result.put("error", "unknown"); } } } } else { // ? error json_result.put("error", this.error); } } catch (FileUploadException e) { FamLog.exception(e, 201204170928l); try { json_result.put("error", "unknown"); } catch (JSONException e1) { FamLog.exception(e1, 201204171037l); } } catch (JSONException e) { FamLog.exception(e, 201204171036l); } JSONArray json_wrapper = new JSONArray(); json_wrapper.put(json_result); this.write(json_wrapper); } return result; }
From source file:hd.controller.AddImageToProjectServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// www . j av a 2s . 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 { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); PrintWriter out = response.getWriter(); try { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { //to do } else { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items = null; try { items = upload.parseRequest(request); } catch (FileUploadException e) { e.printStackTrace(); } Iterator iter = items.iterator(); Hashtable params = new Hashtable(); String fileName = null; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { params.put(item.getFieldName(), item.getString("UTF-8")); } else if (!item.isFormField()) { try { long time = System.currentTimeMillis(); String itemName = item.getName(); fileName = time + itemName.substring(itemName.lastIndexOf("\\") + 1); String RealPath = getServletContext().getRealPath("/") + "images\\" + fileName; File savedFile = new File(RealPath); item.write(savedFile); String localPath = "D:\\Project\\TestHouseDecor-Merge\\web\\images\\" + fileName; // savedFile = new File(localPath); // item.write(savedFile); } catch (Exception e) { e.printStackTrace(); } } } //Init Jpa CategoryJpaController categoryJpa = new CategoryJpaController(emf); StyleJpaController styleJpa = new StyleJpaController(emf); ProjectJpaController projectJpa = new ProjectJpaController(emf); IdeaBookPhotoJpaController photoJpa = new IdeaBookPhotoJpaController(emf); // get Object Category by categoryId int cateId = Integer.parseInt((String) params.get("ddlCategory")); Category cate = categoryJpa.findCategory(cateId); // get Object Style by styleId int styleId = Integer.parseInt((String) params.get("ddlStyle")); Style style = styleJpa.findStyle(styleId); // get Object Project by projectId int projectId = Integer.parseInt((String) params.get("txtProjectId")); Project project = projectJpa.findProject(projectId); project.setStatus(Constant.STATUS_WAIT); projectJpa.edit(project); //Get param String title = (String) params.get("title"); String description = (String) params.get("description"); String url = "images/" + fileName; //Init IdeabookPhoto IdeaBookPhoto photo = new IdeaBookPhoto(title, url, description, cate, style, project); photoJpa.create(photo); url = "ViewMyProjectDetailServlet?txtProjectId=" + projectId; //System HDSystem system = new HDSystem(); system.setNotificationProject(request); response.sendRedirect(url); } } catch (Exception e) { log("Error at AddImageToProjectServlet: " + e.getMessage()); } finally { out.close(); } }
From source file:com.seer.datacruncher.profiler.spring.FileUploadController.java
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Check that we have a file upload request filePath = this.servletContext.getInitParameter("file-upload"); isMultipart = ServletFileUpload.isMultipartContent(request); response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); if (!isMultipart) { return null; }/*from ww w . ja v a2s.c om*/ 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(filePath)); // 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(); String fileName = fi.getName(); String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); // 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); out.print("{success: true, file: \"" + fileName + "\"}"); // out.println("{\"file\": " + fileName + "}"); } } } catch (Exception ex) { System.out.println(ex); } return null; }