List of usage examples for org.apache.commons.fileupload FileItem write
void write(File file) throws Exception;
From source file:it.infn.ct.R_portlet.java
void processInputFile(FileItem item, App_Input 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 {//from ww w . ja va2 s .c om 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:hu.sztaki.lpds.pgportal.portlets.workflow.RealWorkflowPortlet.java
@Override public void doUpload(ActionRequest request, ActionResponse response) { PortletContext context = getPortletContext(); context.log("[FileUploadPortlet] doUpload() called"); try {/*from ww w. j a v a 2 s . c om*/ DiskFileItemFactory factory = new DiskFileItemFactory(); PortletFileUpload pfu = new PortletFileUpload(factory); pfu.setSizeMax(uploadMaxSize); // Maximum upload size pfu.setProgressListener((ProgressListener) new FileUploadProgressListener()); PortletSession ps = request.getPortletSession(); if (ps.getAttribute("uploaded") == null) ps.setAttribute("uploaded", new Vector<String>()); ps.setAttribute("upload", pfu); //get the FileItems String fieldName = null; List fileItems = pfu.parseRequest(request); Iterator iter = fileItems.iterator(); File serverSideFile = null; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); // retrieve hidden parameters if item is a form field if (item.isFormField()) { fieldName = item.getFieldName(); } else { // item is not a form field, do file upload Hashtable<String, ProgressListener> tmp = (Hashtable<String, ProgressListener>) ps .getAttribute("uploads", ps.APPLICATION_SCOPE); String s = item.getName(); s = FilenameUtils.getName(s); ps.setAttribute("uploading", s); String tempDir = System.getProperty("java.io.tmpdir") + "/uploads/" + request.getRemoteUser(); File f = new File(tempDir); if (!f.exists()) f.mkdirs(); serverSideFile = new File(tempDir, s); item.write(serverSideFile); item.delete(); context.log("[FileUploadPortlet] - file " + s + " uploaded successfully to " + tempDir); // file upload to storage try { Hashtable h = new Hashtable(); h.put("portalURL", PropertyLoader.getInstance().getProperty("service.url")); h.put("userID", request.getRemoteUser()); String uploadField = ""; // retrieve hidden parameters if item is a form field for (FileItem item0 : (List<FileItem>) fileItems) { if (item0.isFormField()) h.put(item0.getFieldName(), item0.getString()); else uploadField = item0.getFieldName(); } Hashtable hsh = new Hashtable(); ServiceType st = InformationBase.getI().getService("storage", "portal", hsh, new Vector()); PortalStorageClient psc = (PortalStorageClient) Class.forName(st.getClientObject()) .newInstance(); psc.setServiceURL(st.getServiceUrl()); psc.setServiceID("/upload"); if (serverSideFile != null) { psc.fileUpload(serverSideFile, uploadField, h); } } catch (Exception ex) { response.setRenderParameter("full", "error.upload"); ex.printStackTrace(); return; } ((Vector<String>) ps.getAttribute("uploaded")).add(s); } } // ps.removeAttribute("uploads",ps.APPLICATION_SCOPE); ps.setAttribute("finaluploads", ""); } catch (FileUploadException fue) { response.setRenderParameter("full", "error.upload"); fue.printStackTrace(); context.log("[FileUploadPortlet] - failed to upload file - " + fue.toString()); return; } catch (Exception e) { e.printStackTrace(); response.setRenderParameter("full", "error.exception"); context.log("[FileUploadPortlet] - failed to upload file - " + e.toString()); return; } response.setRenderParameter("full", "action.succesfull"); }
From source file:admin.controller.ServletEditCategories.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from ww w .j a v a 2 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 */ @Override 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 { upload_path = AppConstants.ORG_CATEGORIES_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(AppConstants.TMP_FOLDER)); // 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("category_name")) { category_name = fi.getString(); } if (field_name.equals("category_id")) { category_id = fi.getString(); } if (field_name.equals("organization")) { organization_id = fi.getString(); upload_path = upload_path + File.separator + organization_id; } } else { field_name = fi.getFieldName(); file_name = fi.getName(); if (file_name != "") { File uploadDir = new File(upload_path); if (!uploadDir.exists()) { uploadDir.mkdirs(); } // int inStr = file_name.indexOf("."); // String Str = file_name.substring(0, inStr); // // file_name = category_name + "_" + Str + ".jpeg"; file_name = category_name + "_" + file_name; boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); String filePath = upload_path + File.separator + file_name; File storeFile = new File(filePath); fi.write(storeFile); out.println("Uploaded Filename: " + filePath + "<br>"); } } } categories.editCategories(Integer.parseInt(category_id), Integer.parseInt(organization_id), category_name, file_name); response.sendRedirect(request.getContextPath() + "/admin/categories.jsp"); 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, "Exception while editing categories", ex); } finally { try { out.close(); } catch (Exception e) { } } }
From source file:it.fub.jardin.server.Upload.java
/** * Processa i file ricevuti dal dialog di upload. Le azioni da eseguire con i * file sono definite dal campo FIELD_TYPE del dialog di upload. I nomi delle * azioni da eseguire sono definite nelle proprieta statiche del dialog di * upload (dove sono precedute dalla stringa "TYPE_") * /*from w w w .j a v a2 s .co m*/ * @param item * il singolo campo contenente il nome del file da processare * @return una stringa con l'esito dell'operazione compiuta sul file. Un * risultato positivo preceduto dalla stringa definita nelle * propriet statiche del dialog di upload */ private String processUploadedFile(final FileItem item) { if (!this.isContentTypeAcceptable(item)) { return "Errore. Il file da caricare non di un tipo consentito"; } if (!this.isSizeAcceptable(item)) { return "Errore. Il file da caricare troppo grande. Dimensione massima di upload: " + MAX_SIZE + " byte"; } if (this.ts.length() != 1) { return "Il separatore di testo deve essere composto da un carattere"; } else if (this.fs.length() != 1) { return "Il separatore di campo deve essere composto da un carattere"; } else if (this.ts.compareToIgnoreCase(this.fs) == 0) { return "Il separatore di campo e il separatore di testo non possono essere uguali"; } String name = item.getName(); File f = null; if (this.resultset > 0) { name = this.resultset + "_" + name; } try { if (this.type != null) { String root = this.getServletContext().getRealPath("/"); /* Decisione del posto dove salvare il file */ if (this.type.compareTo(UploadDialog.TYPE_TEMPLATE) == 0) { f = new File(root + Template.TEMPLATE_DIR + name); } else if ((this.type.compareTo(UploadDialog.TYPE_IMPORT) == 0) || (this.type.compareTo(UploadDialog.TYPE_INSERT) == 0)) { f = File.createTempFile(name, ""); } else { // Log.warn("Azione da eseguire con il file '" + this.type // + "' non riconosciuta"); return "Errore. Non possibile decidere quale azione eseguire con il file"; } /* Creazione del file sul server */ item.write(f); /* Decisione delle azioni da eseguire con il file */ if (this.type.compareToIgnoreCase(UploadDialog.TYPE_IMPORT) == 0) { dbUtils.importFile(this.mailUtility, this.credentials, this.resultset, f, this.ts, this.fs, this.tipologia, UploadDialog.TYPE_IMPORT, this.condition, "aggiornamento"); return UploadDialog.SUCCESS + "Importazione dati avvenuta con successo"; } else if (this.type.compareToIgnoreCase(UploadDialog.TYPE_INSERT) == 0) { dbUtils.importFile(this.mailUtility, this.credentials, this.resultset, f, this.ts, this.fs, this.tipologia, UploadDialog.TYPE_INSERT, this.condition, "inserimento"); return UploadDialog.SUCCESS + "Importazione dati avvenuta con successo"; } else { return UploadDialog.SUCCESS + "Upload del file avvenuto con successo"; } } else { /* Non esiste specifica del campo type */ // Log.warn("Manca il tipo di azione da eseguire con il file"); return "Errore. Non possibile decidere quale azione eseguire con il file"; } } catch (HiddenException e) { // Log.warn("Errore durante il caricamento dei dati", e); return "Errore. " + e.getLocalizedMessage(); } catch (VisibleException e) { // Log.warn(e.getMessage()); return e.getMessage(); } catch (Exception e) { // Log.warn("Errore durante l'upload del file", e); e.printStackTrace(); return "Errore. Impossibile salvare il file sul server"; } }
From source file:com.siberhus.web.ckeditor.servlet.StandardFileManagerConnectorServlet.java
private StreamingResult execute(HttpServletRequest request, HttpServletResponse response, String command, String currentFolder, String userSpace, boolean uploadOnly) { // uploadOnly = false by default if (command == null) command = "GetFolders"; //default command if (currentFolder == null) currentFolder = ""; CkeditorConfig config = CkeditorConfigurationHolder.config(); String baseDir = StringUtils.isNotBlank(config.upload().basedir(request)) ? config.upload().basedir(request) : CkeditorTagConfig.DEFAULT_BASEDIR; baseDir = PathUtils.checkSlashes(baseDir, "L+ R+", true); String spaceDir = PathUtils.sanitizePath(userSpace); spaceDir = PathUtils.checkSlashes(spaceDir, "L- R+", true); String type = request.getParameter("Type"); String currentPath = baseDir + spaceDir + type + currentFolder; String currentUrl = null;/* w ww .j av a2 s.com*/ String realPath = null; // Use a directory outside of the application space? String userDefinedBaseUrl = config.upload().baseurl(request); if (StringUtils.isNotBlank(userDefinedBaseUrl)) { String baseUrl = PathUtils.checkSlashes(userDefinedBaseUrl, "R-", true); baseUrl += baseDir; currentUrl = baseUrl + spaceDir + type + currentFolder; // realPath = currentPath; } else { currentUrl = request.getContextPath() + currentPath; } realPath = request.getSession().getServletContext().getRealPath(currentPath); File finalDir = new File(realPath); if (!finalDir.exists()) { finalDir.mkdirs(); } log.debug("userSpace = {}", userSpace); log.debug("Command = {}", command); log.debug("CurrentFolder = {}", currentFolder); log.debug("Type = {}", type); log.debug("finalDir = {}", finalDir); int errorNo = 0; String errorMsg = null; StreamingResult resolution = null; if ("GetFolders".equals(command)) { String xml = "<Connector command=\"" + command + "\" resourceType=\"" + type + "\">\n"; xml += "\t<CurrentFolder path=\"" + currentFolder + "\" url=\"" + currentUrl + "\"/>\n"; List<File> dirs = new ArrayList<File>(); for (File f : finalDir.listFiles()) { if (f.isDirectory()) { dirs.add(f); } } Collections.sort(dirs); xml += "\t\t<Folders>\n"; for (File f : dirs) { xml += "\t\t\t<Folder name=\"" + f.getName() + "\"/>\n"; } xml += "\t\t</Folders>\n"; xml += "</Connector>\n"; resolution = new StreamingResult("text/xml", xml); } else if ("GetFoldersAndFiles".equals(command)) { String xml = "<Connector command=\"" + command + "\" resourceType=\"" + type + "\">\n"; xml += "\t<CurrentFolder path=\"" + currentFolder + "\" url=\"" + currentUrl + "\"/>\n"; List<File> dirs = new ArrayList<File>(); List<File> files = new ArrayList<File>(); for (File f : finalDir.listFiles()) { if (f.isDirectory()) { dirs.add(f); } else { files.add(f); } } Collections.sort(dirs); Collections.sort(files); xml += "\t\t<Folders>\n"; for (File f : dirs) { xml += "\t\t\t<Folder name=\"" + f.getName() + "\"/>\n"; } xml += "\t\t</Folders>\n"; xml += "\t\t<Files>\n"; for (File f : files) { xml += "\t\t\t<File name=\"" + f.getName() + "\" size=\"" + (f.length() / 1024) + "\"/>\n"; } xml += "\t\t</Files>\n"; xml += "</Connector>\n"; resolution = new StreamingResult("text/xml", xml); } else if ("CreateFolder".equals(command)) { String newFolderName = request.getParameter("NewFolderName"); File newFinalDir = new File(finalDir, newFolderName); errorNo = ERROR_NOERROR; if (newFinalDir.exists()) { errorNo = ERROR_FOLDER_EXISTS; } else { try { if (newFinalDir.mkdir()) { errorNo = ERROR_NOERROR; } else { errorNo = ERROR_INVALID_FOLDER_NAME; } } catch (SecurityException se) { errorNo = ERROR_NO_CREATE_PERMISSIONS; } } resolution = renderXmlResult(command, type, currentFolder, currentUrl, errorNo); } else if ("DeleteFile".equals(command)) { String fileName = request.getParameter("FileName"); File fileFinalName = new File(finalDir, fileName); errorNo = ERROR_NOERROR; if (fileFinalName.exists()) { try { if (fileFinalName.delete()) { errorNo = ERROR_NOERROR; } else { errorNo = ERROR_INVALID_FILE_NAME; } } catch (SecurityException se) { errorNo = ERROR_NO_CREATE_PERMISSIONS; } } else { errorNo = ERROR_INVALID_FILE_NAME; } resolution = renderXmlResult(command, type, currentFolder, currentUrl, errorNo); } else if ("DeleteFolder".equals(command)) { String folderName = request.getParameter("FolderName"); File folderFinalName = new File(finalDir, folderName); errorNo = ERROR_NOERROR; if (folderFinalName.exists() && folderFinalName.isDirectory()) { try { org.apache.commons.io.FileUtils.deleteDirectory(folderFinalName); errorNo = ERROR_NOERROR; } catch (IOException se) { // errorNo = ERROR_NO_CREATE_PERMISSIONS; errorNo = ERROR_CANNOT_DELETE; } } else { errorNo = ERROR_INVALID_FOLDER_NAME; } resolution = renderXmlResult(command, type, currentFolder, currentUrl, errorNo); } else if ("RenameFile".equals(command)) { String oldName = request.getParameter("FileName"); String newName = request.getParameter("NewName"); File oldFinalName = new File(finalDir, oldName); File newFinalName = new File(finalDir, newName); errorNo = ERROR_NOERROR; if (!newFinalName.exists() && FileUtils.isFileAllowed(newName, type)) { try { if (oldFinalName.renameTo(newFinalName)) { errorNo = ERROR_NOERROR; } else { errorNo = ERROR_INVALID_FILE_NAME; } } catch (SecurityException se) { errorNo = ERROR_NO_CREATE_PERMISSIONS; } } else { errorNo = ERROR_INVALID_FILE_NAME; } resolution = renderXmlResult(command, type, currentFolder, currentUrl, errorNo); } else if ("RenameFolder".equals(command)) { String oldName = request.getParameter("FolderName"); String newName = request.getParameter("NewName"); File oldFinalName = new File(finalDir, oldName); File newFinalName = new File(finalDir, newName); errorNo = ERROR_NOERROR; if (!newFinalName.exists()) { try { if (oldFinalName.renameTo(newFinalName)) { errorNo = ERROR_NOERROR; } else { errorNo = ERROR_INVALID_FOLDER_NAME; } } catch (SecurityException se) { errorNo = ERROR_NO_CREATE_PERMISSIONS; } } else { errorNo = ERROR_INVALID_FOLDER_NAME; } resolution = renderXmlResult(command, type, currentFolder, currentUrl, errorNo); } else if ("FileUpload".equals(command)) { errorNo = ERROR_NOERROR; errorMsg = ""; // String uploadFieldName = uploadOnly ? "upload" : "NewFile"; String newName = ""; boolean overwrite = config.upload().overwrite(); if (isUploadEnabled(type)) { if (!"POST".equals(request.getMethod())) { errorNo = ERROR_CUSTOM; errorMsg = "INVALID CALL"; } else { MultipartServletRequest mrequest = (MultipartServletRequest) request; FileItem fileItem = mrequest.getFileItem("NewFile"); ; // if("upload".equals(uploadFieldName)){ // fileItem = mrequest.getFileItem("upload"); // }else{ // fileItem = mrequest.getFileItem("newfile"); // } if (fileItem == null) { errorNo = ERROR_CUSTOM; errorMsg = "INVALID FILE"; } else { errorNo = ERROR_NOERROR; newName = fileItem.getName(); String fileBaseName = FilenameUtils.getBaseName(newName); String fileExt = FilenameUtils.getExtension(newName); if (FileUtils.isAllowed(fileExt, type)) { File fileToSave = new File(finalDir, newName); if (!overwrite) { int idx = 1; while (fileToSave.exists()) { errorNo = ERROR_FILE_RENAMED; newName = fileBaseName + "(" + idx + ")." + fileExt; fileToSave = new File(finalDir, newName); idx++; } } try { fileItem.write(fileToSave); } catch (Exception e) { errorNo = ERROR_CUSTOM; errorMsg = "UNABLE TO SAVE FILE!"; } } else { errorNo = ERROR_INVALID_FILE_TYPE; errorMsg = "INVALID FILE TYPE"; } } } } else { errorNo = ERROR_CUSTOM; errorMsg = "UPLOADS ARE DISABLED!"; } String html = "<script type=\"text/javascript\">\n"; if (uploadOnly) { if (StringUtils.isNotBlank(config.upload().baseurl(request))) { currentUrl = request.getContextPath() + currentUrl; } String fname = StringUtils.isNotBlank(errorMsg) ? "" : currentUrl + newName; html += "\twindow.parent.CKEDITOR.tools.callFunction(" + request.getParameter("CKEditorFuncNum") + ", '" + fname + "', '" + errorMsg + "');"; } else { html += "\twindow.parent.frames['frmUpload'].OnUploadCompleted(" + errorNo + ", '" + newName + "');"; } html += "</script>\n"; resolution = new StreamingResult("text/html", html); } response.setHeader("Cache-Control", "no-cache"); log.debug("errorNo = {}", errorNo); log.debug("errorMsg = {}", errorMsg); if (resolution != null) { return resolution; } throw new IllegalArgumentException("Unkown command: " + command); }
From source file:com.stratelia.webactiv.agenda.servlets.AgendaRequestRouter.java
private File processFormUpload(AgendaSessionController agendaSc, HttpServletRequest request) { String logicalName = ""; String tempFolderName = ""; String tempFolderPath = ""; String fileType = ""; long fileSize = 0; File fileUploaded = null;/*from ww w . ja v a 2s .c om*/ try { List<FileItem> items = HttpRequest.decorate(request).getFileItems(); FileItem fileItem = FileUploadUtil.getFile(items, "fileCalendar"); if (fileItem != null) { logicalName = fileItem.getName(); if (logicalName != null) { logicalName = logicalName.substring(logicalName.lastIndexOf(File.separator) + 1, logicalName.length()); // Name of temp folder: timestamp and userId tempFolderName = new Long(new Date().getTime()).toString() + "_" + agendaSc.getUserId(); // Mime type of the file fileType = fileItem.getContentType(); fileSize = fileItem.getSize(); // Directory Temp for the uploaded file tempFolderPath = FileRepositoryManager.getAbsolutePath(agendaSc.getComponentId()) + GeneralPropertiesManager.getString("RepositoryTypeTemp") + File.separator + tempFolderName; if (!new File(tempFolderPath).exists()) { FileRepositoryManager.createAbsolutePath(agendaSc.getComponentId(), GeneralPropertiesManager.getString("RepositoryTypeTemp") + File.separator + tempFolderName); } // Creation of the file in the temp folder fileUploaded = new File(FileRepositoryManager.getAbsolutePath(agendaSc.getComponentId()) + GeneralPropertiesManager.getString("RepositoryTypeTemp") + File.separator + tempFolderName + File.separator + logicalName); fileItem.write(fileUploaded); // Is a real file ? if (fileSize > 0) { SilverTrace.debug("agenda", "AgendaRequestRouter.processFormUpload()", "root.MSG_GEN_PARAM_VALUE", "fileUploaded = " + fileUploaded + " fileSize=" + fileSize + " fileType=" + fileType); } } } } catch (Exception e) { // Other exception SilverTrace.warn("agenda", "AgendaRequestRouter.processFormUpload()", "root.EX_LOAD_ATTACHMENT_FAILED", e); } return fileUploaded; }
From source file:admin.controller.ServletEditPersonality.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w. j av 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 */ @Override 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 { uploadPath = AppConstants.BRAND_IMAGES_HOME; deletePath = 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(AppConstants.TMP_FOLDER)); // 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 fieldName = fi.getFieldName(); if (fieldName.equals("brandname")) { brandname = fi.getString(); } if (fieldName.equals("brandid")) { brandid = fi.getString(); } if (fieldName.equals("look")) { lookid = fi.getString(); } file_name_to_delete = brand.getFileName(Integer.parseInt(brandid)); } else { fieldName = fi.getFieldName(); fileName = fi.getName(); File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdirs(); } // int inStr = fileName.indexOf("."); // String Str = fileName.substring(0, inStr); // // fileName = brandname + "_" + Str + ".jpeg"; fileName = brandname + "_" + fileName; boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); String file_path = uploadPath + File.separator + fileName; String delete_path = deletePath + File.separator + file_name_to_delete; File deleteFile = new File(delete_path); deleteFile.delete(); File storeFile = new File(file_path); fi.write(storeFile); out.println("Uploaded Filename: " + filePath + "<br>"); } } brand.editBrands(Integer.parseInt(brandid), brandname, Integer.parseInt(lookid), fileName); response.sendRedirect(request.getContextPath() + "/admin/brandpersonality.jsp"); // request_dispatcher = request.getRequestDispatcher("/admin/looks.jsp"); // request_dispatcher.forward(request, response); 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 { out.close(); } }
From source file:controllers.controller.java
private void insertarObjetoArchivo(HttpSession session, HttpServletRequest request, HttpServletResponse response, QUID quid, PrintWriter out, HashMap parameters, LinkedList filesToUpload, String FormFrom) throws Exception { if (parameters.get("idTipoArchivo") == null || parameters.get("idTipoArchivo").equals("")) { this.getServletConfig().getServletContext() .getRequestDispatcher("" + PageParameters.getParameter("msgUtil") + "/msgNRedirect.jsp?title=Error&type=error&msg=Seleccione el tipo de archivo.&url=" + PageParameters.getParameter("mainContext") + PageParameters.getParameter("gui") + "/Insert_ObjetoArchivo.jsp?" + WebUtil.encode(session, "imix") + "=" + WebUtil.encode(session, UTime.getTimeMilis()) + "_param_nombreObjeto=" + parameters.get("nombreObjeto") + "_param_idObjeto=" + parameters.get("idObjeto")) .forward(request, response); } else if (parameters.get("nombreArchivo") == null || parameters.get("nombreArchivo").equals("")) { this.getServletConfig().getServletContext() .getRequestDispatcher("" + PageParameters.getParameter("msgUtil") + "/msgNRedirect.jsp?title=Error&type=error&msg=Escriba el nombre del archivo.&url=" + PageParameters.getParameter("mainContext") + PageParameters.getParameter("gui") + "/Insert_ObjetoArchivo.jsp?" + WebUtil.encode(session, "imix") + "=" + WebUtil.encode(session, UTime.getTimeMilis()) + "_param_nombreObjeto=" + parameters.get("nombreObjeto") + "_param_idObjeto=" + parameters.get("idObjeto")) .forward(request, response); } else if (parameters.get("descripcion") == null || parameters.get("descripcion").toString().trim().equals("")) { this.getServletConfig().getServletContext() .getRequestDispatcher("" + PageParameters.getParameter("msgUtil") + "/msgNRedirect.jsp?title=Error&type=error&msg=Escriba una descripcin.&url=" + PageParameters.getParameter("mainContext") + PageParameters.getParameter("gui") + "/Insert_ObjetoArchivo.jsp?" + WebUtil.encode(session, "imix") + "=" + WebUtil.encode(session, UTime.getTimeMilis()) + "_param_nombreObjeto=" + parameters.get("nombreObjeto") + "_param_idObjeto=" + parameters.get("idObjeto")) .forward(request, response); } else if (parameters.get("tipoAcceso").equals("")) { this.getServletConfig().getServletContext().getRequestDispatcher("" + PageParameters.getParameter("msgUtil") + "/msgNRedirect.jsp?title=Error&type=error&msg=Seleccione el tipo de acceso para el archivo.&url=" + PageParameters.getParameter("mainContext") + PageParameters.getParameter("gui") + "/Insert_ObjetoArchivo.jsp?" + WebUtil.encode(session, "imix") + "=" + WebUtil.encode(session, UTime.getTimeMilis()) + "_param_nombreObjeto=" + parameters.get("nombreObjeto") + "_param_idObjeto=" + parameters.get("idObjeto")) .forward(request, response); } else if (filesToUpload.isEmpty()) { this.getServletConfig().getServletContext().getRequestDispatcher("" + PageParameters.getParameter("msgUtil") + "/msgNRedirect.jsp?title=Error&type=error&msg=No ha seleccionado ningn archivo.&url=" + PageParameters.getParameter("mainContext") + PageParameters.getParameter("gui") + "/Insert_ObjetoArchivo.jsp?" + WebUtil.encode(session, "imix") + "=" + WebUtil.encode(session, UTime.getTimeMilis()) + "_param_nombreObjeto=" + parameters.get("nombreObjeto") + "_param_idObjeto=" + parameters.get("idObjeto")) .forward(request, response); } else if (!filesToUpload.isEmpty()) { String idObjeto = WebUtil.decode(session, parameters.get("idObjeto").toString()); String fechaActualizacion = UTime.calendar2SQLDateFormat(Calendar.getInstance()); String descripcion = WebUtil.decode(session, parameters.get("descripcion").toString()); String ubicacionFisica = PageParameters.getParameter("folderDocs"); String idTipoArchivo = WebUtil.decode(session, parameters.get("idTipoArchivo").toString()); String nombreObjeto = WebUtil.decode(session, parameters.get("nombreObjeto").toString()); String keyWords = parameters.get("keywords").toString(); String nombreArchivo = parameters.get("nombreArchivo").toString(); String FK_ID_Plantel = session.getAttribute("FK_ID_Plantel").toString(); //File verifyFolder = new File(PageParameters.getParameter("folderDocs")); File verifyFolder = new File(ubicacionFisica); if (!verifyFolder.exists()) { verifyFolder.mkdirs();/* w w w. j ava2 s . co m*/ } int sucess = 0; for (int i = 0; i < filesToUpload.size(); i++) { FileItem itemToUpload = null; itemToUpload = (FileItem) filesToUpload.get(i); String extension = FileUtil.getExtension(itemToUpload.getName()); String hashName = JHash.getFileDigest(itemToUpload.get(), "MD5") + extension; long tamanio = itemToUpload.getSize(); if (this.validarDocumentExtension(session, request, response, quid, out, extension)) { File fileToWrite = new File(ubicacionFisica, hashName); Transporter tport = quid.insertArchivo4Objeto(idObjeto, nombreObjeto, idTipoArchivo, nombreArchivo, descripcion, ubicacionFisica, extension, fechaActualizacion, tamanio, WebUtil.decode(session, parameters.get("tipoAcceso").toString()).toLowerCase(), keyWords, hashName, FK_ID_Plantel); if (tport.getCode() == 0) { if (!fileToWrite.exists()) { itemToUpload.write(fileToWrite); } sucess += 1; } } else { sucess = -1; } } if (sucess != -1) { this.getServletConfig().getServletContext() .getRequestDispatcher("" + PageParameters.getParameter("msgUtil") + "/msgNRedirect.jsp?title=Operacin Exitosa&type=info&msg=Se han guardado " + sucess + " de " + filesToUpload.size() + " archivos.&url=" + PageParameters.getParameter("mainContext") + PageParameters.getParameter("gui") + "/Insert_ObjetoArchivo.jsp?" + WebUtil.encode(session, "imix") + "=" + WebUtil.encode(session, UTime.getTimeMilis()) + "_param_nombreObjeto=" + parameters.get("nombreObjeto") + "_param_idObjeto=" + parameters.get("idObjeto")) .forward(request, response); } } }
From source file:com.mingsoft.basic.servlet.UploadServlet.java
/** * ?post/* ww w .j av a 2 s . com*/ * @param req HttpServletRequest * @param res HttpServletResponse * @throws ServletException ? * @throws IOException ? */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html;charset=utf-8"); PrintWriter out = res.getWriter(); String uploadPath = this.getServletContext().getRealPath(File.separator); // String isRename = "";// ???? true:??? String _tempPath = req.getServletContext().getRealPath(File.separator) + "temp";// FileUtil.createFolder(_tempPath); File tempPath = new File(_tempPath); // int maxSize = 1000000; // ??,?? 1000000/1024=0.9M //String allowedFile = ".jpg,.gif,.png,.zip"; // ? String deniedFile = ".exe,.com,.cgi,.asp"; // ?? DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory // ????? factory.setSizeThreshold(4096); // the location for saving data that is larger than getSizeThreshold() // ?SizeThreshold? factory.setRepository(tempPath); ServletFileUpload upload = new ServletFileUpload(factory); // maximum size before a FileUploadException will be thrown try { List fileItems = upload.parseRequest(req); Iterator iter = fileItems.iterator(); // ???? String regExp = ".+\\\\(.+)$"; // String[] errorType = deniedFile.split(","); Pattern p = Pattern.compile(regExp); String outPath = ""; //?? while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.getFieldName().equals("uploadPath")) { outPath += item.getString(); uploadPath += outPath; } else if (item.getFieldName().equals("isRename")) { isRename = item.getString(); } else if (item.getFieldName().equals("maxSize")) { maxSize = Integer.parseInt(item.getString()) * 1048576; } else if (item.getFieldName().equals("allowedFile")) { // allowedFile = item.getString(); } else if (item.getFieldName().equals("deniedFile")) { deniedFile = item.getString(); } else if (!item.isFormField()) { // ??? String name = item.getName(); long size = item.getSize(); if ((name == null || name.equals("")) && size == 0) continue; try { // ?? 1000000/1024=0.9M upload.setSizeMax(maxSize); // ? // ? String fileName = System.currentTimeMillis() + name.substring(name.indexOf(".")); String savePath = uploadPath + File.separator; FileUtil.createFolder(savePath); // ??? if (StringUtil.isBlank(isRename) || Boolean.parseBoolean(isRename)) { savePath += fileName; outPath += fileName; } else { savePath += name; outPath += name; } item.write(new File(savePath)); out.print(outPath.trim()); logger.debug("upload file ok return path " + outPath); out.flush(); out.close(); } catch (Exception e) { this.logger.debug(e); } } } } catch (FileUploadException e) { this.logger.debug(e); } }
From source file:hudson.FilePath.java
/** * Place the data from {@link FileItem} into the file location specified by this {@link FilePath} object. *//*from www . ja v a 2s . c om*/ public void copyFrom(FileItem file) throws IOException, InterruptedException { if (channel == null) { try { file.write(new File(remote)); } catch (IOException e) { throw e; } catch (Exception e) { throw new IOException2(e); } } else { InputStream i = file.getInputStream(); OutputStream o = write(); try { IOUtils.copy(i, o); } finally { o.close(); i.close(); } } }