List of usage examples for org.apache.commons.fileupload FileItem write
void write(File file) throws Exception;
From source file:com.javaweb.controller.ThemTinTucServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request servlet request//w w w . ja va2 s. c om * @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, ParseException { response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("UTF-8"); //response.setCharacterEncoding("UTF-8"); HttpSession session = request.getSession(); // session.removeAttribute("errorreg"); String TieuDe = "", NoiDung = "", ngaydang = "", GhiChu = "", fileName = ""; int idloaitin = 0, idTK = 0; TintucService tintucservice = new TintucService(); //File upload String folderupload = getServletContext().getInitParameter("file-upload"); String rootPath = getServletContext().getRealPath("/"); filePath = rootPath + folderupload; isMultipart = ServletFileUpload.isMultipartContent(request); response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); 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("C:\\Windows\\Temp\\")); // 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(); //change file name fileName = FileService.ChangeFileName(fileName); // 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.println("Uploaded Filename: " + fileName + "<br>"); } if (fi.isFormField()) { if (fi.getFieldName().equalsIgnoreCase("TieuDe")) { TieuDe = fi.getString("UTF-8"); } else if (fi.getFieldName().equalsIgnoreCase("NoiDung")) { NoiDung = fi.getString("UTF-8"); } else if (fi.getFieldName().equalsIgnoreCase("NgayDang")) { ngaydang = fi.getString("UTF-8"); } else if (fi.getFieldName().equalsIgnoreCase("GhiChu")) { GhiChu = fi.getString("UTF-8"); } else if (fi.getFieldName().equalsIgnoreCase("loaitin")) { idloaitin = Integer.parseInt(fi.getString("UTF-8")); } else if (fi.getFieldName().equalsIgnoreCase("idtaikhoan")) { idTK = Integer.parseInt(fi.getString("UTF-8")); } } } } catch (Exception ex) { System.out.println(ex); } Date NgayDang = new SimpleDateFormat("yyyy-MM-dd").parse(ngaydang); Tintuc tintuc = new Tintuc(idloaitin, idTK, fileName, TieuDe, NoiDung, NgayDang, GhiChu); boolean rs = tintucservice.InsertTintuc(tintuc); if (rs) { session.setAttribute("kiemtra", "1"); String url = "ThemTinTuc.jsp"; response.sendRedirect(url); } else { session.setAttribute("kiemtra", "0"); String url = "ThemTinTuc.jsp"; response.sendRedirect(url); } // try (PrintWriter out = response.getWriter()) { // /* TODO output your page here. You may use following sample code. */ // out.println("<!DOCTYPE html>"); // out.println("<html>"); // out.println("<head>"); // out.println("<title>Servlet ThemTinTucServlet</title>"); // out.println("</head>"); // out.println("<body>"); // out.println("<h1>Servlet ThemTinTucServlet at " + request.getContextPath() + "</h1>"); // out.println("</body>"); // out.println("</html>"); // } }
From source file:com.rapidsist.portal.cliente.editor.ConnectorServlet.java
/** * Manage the Post requests (FileUpload).<br> * * The servlet accepts commands sent in the following format:<br> * connector?Command=FileUpload&Type=ResourceType&CurrentFolder=FolderPath<br><br> * It store the file (renaming it in case a file with the same name exists) and then return an HTML file * with a javascript command in it./*from w w w .j a v a2 s . c o m*/ * */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("PASO POR EL METODO doPost DEL SERVLET ConnectorServlet"); response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String commandStr = request.getParameter("Command"); String typeStr = request.getParameter("Type"); String currentFolderStr = request.getParameter("CurrentFolder"); String currentPath = baseDir + typeStr + currentFolderStr; String currentDirPath = getServletContext().getRealPath(currentPath); String retVal = "0"; String newName = ""; if (!commandStr.equals("FileUpload")) retVal = "203"; else { DiskFileUpload upload = new DiskFileUpload(); try { List items = upload.parseRequest(request); Map fields = new HashMap(); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) fields.put(item.getFieldName(), item.getString()); else fields.put(item.getFieldName(), item); } FileItem uplFile = (FileItem) fields.get("NewFile"); String fileNameLong = uplFile.getName(); fileNameLong = fileNameLong.replace('\\', '/'); String[] pathParts = fileNameLong.split("/"); String fileName = pathParts[pathParts.length - 1]; String nameWithoutExt = getNameWithoutExtension(fileName); String ext = getExtension(fileName); File pathToSave = new File(currentDirPath, fileName); int counter = 1; while (pathToSave.exists()) { newName = nameWithoutExt + "(" + counter + ")" + "." + ext; retVal = "201"; pathToSave = new File(currentDirPath, newName); counter++; } uplFile.write(pathToSave); } catch (Exception ex) { retVal = "203"; } } out.println("<script type=\"text/javascript\">"); out.println("window.parent.frames['frmUpload'].OnUploadCompleted(" + retVal + ",'" + newName + "');"); out.println("</script>"); out.flush(); out.close(); }
From source file:business.controllers.UploadImageController.java
public void uploadImage(HttpServletRequest request, HttpServletResponse response, List formItems) throws IOException { BusinessChatHandler handler = new BusinessChatHandler(); Long imageId;/* www .j a va2s. c o m*/ try { imageId = (Long) handler.getImageId(); } catch (TException ex) { imageId = 0L; logger.error("get image id:" + ex); } String filePath = ""; String uploadPath = "../resources/" + UploadConstant.UPLOAD_DIRECTORY; // parses the request's content to extract file data Iterator iter = formItems.iterator(); String userId = ""; String fileName = ""; File storeFile = null; // iterates over form's fields while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); // processes only fields that are not form fields if (!item.isFormField()) { try { fileName = new File(item.getName()).getName(); String extensionImage = ""; for (int i = fileName.length() - 1; i >= 0; i--) { if (fileName.charAt(i) == '.') { break; } else { extensionImage = fileName.charAt(i) + extensionImage; } } //tao file name moi // fileName = imageId + "." + extensionImage; // fileName = imageId + "_" + fileName; filePath = uploadPath + File.separator + fileName; storeFile = new File(filePath); // saves the file on disk item.write(storeFile); } catch (Exception ex) { logger.error("error when write image"); } } else if (item.getFieldName().equals("userId")) { userId = item.getString(); } } if (storeFile != null) { //userID_imageGen_fileNameofUser.jpg fileName = userId + "_" + imageId + "_" + fileName; filePath = uploadPath + File.separator + fileName; File newNameImage = new File(filePath); storeFile.renameTo(newNameImage); } response.setHeader("Access-Control-Allow-Origin", "*"); response.setContentType("text/html"); response.getWriter().println(filePath); }
From source file:fr.cnes.sitools.ext.jeobrowser.upload.JeoUploadResource.java
/** * Upload a File contained in the given entity to the temporary folder of the * Sitools Server at the given directory name * // w ww .j a v a 2 s .com * @param entity * the file to upload * @param directoryName * the directory * @return a Representation * */ private Representation uploadFile(Representation entity, String directoryName) { Representation rep = null; if (entity != null) { settings = ((SitoolsApplication) getApplication()).getSettings(); File storeDirectory = new File(settings.getTmpFolderUrl() + "/" + directoryName); storeDirectory.mkdirs(); if (MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) { // storeDirectory = "c:\\temp\\"; // The Apache FileUpload project parses HTTP requests which // conform to RFC 1867, "Form-based File Upload in HTML". That // is, if an HTTP request is submitted using the POST method, // and with a content type of "multipart/form-data", then // FileUpload can parse that request, and get all uploaded files // as FileItem. // 1/ Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1000240); // 2/ Create a new file upload handler based on the Restlet // FileUpload extension that will parse Restlet requests and // generates FileItems. RestletFileUpload upload = new RestletFileUpload(factory); List<FileItem> items; // 3/ Request is parsed by the handler which generates a // list of FileItems try { items = upload.parseRequest(getRequest()); } catch (FileUploadException e1) { e1.printStackTrace(); items = new ArrayList<FileItem>(); } // Says if at least one file has been handled boolean found = false; // List the files that haven't been uploaded List<String> oops = new ArrayList<String>(); // count the number files int nbFiles = 0; for (final Iterator<FileItem> it = items.iterator(); it.hasNext();) { FileItem fi = it.next(); // Process only the items that *really* contains an uploaded // file and save them on disk if (fi.getName() != null) { found = true; nbFiles++; File file = new File(storeDirectory, fi.getName()); try { fi.write(file); filePath = file.getAbsolutePath(); } catch (Exception e) { System.out.println( "Can't write the content of " + file.getPath() + " due to " + e.getMessage()); oops.add(file.getName()); } } else { // This is a simple text form input. System.out.println(fi.getFieldName() + " " + fi.getString()); } } // Once handled, you can send a report to the user. StringBuilder sb = new StringBuilder(); if (found) { sb.append(nbFiles); if (nbFiles > 1) { sb.append(" files sent"); } else { sb.append(" file sent"); } if (!oops.isEmpty()) { sb.append(", ").append(oops.size()); if (oops.size() > 1) { sb.append(" files in error:"); } else { sb.append(" file in error:"); } for (int i = 0; i < oops.size(); i++) { if (i > 0) { sb.append(","); } sb.append(" \"").append(oops.get(i)).append("\""); } } sb.append("."); rep = new StringRepresentation(sb.toString(), MediaType.TEXT_PLAIN); } else { // Some problem occurs, sent back a simple line of text. rep = new StringRepresentation("no file uploaded", MediaType.TEXT_PLAIN); } } else { String fileName = "tmp_zip.zip"; String resourceRef = RIAPUtils.getRiapBase() + settings.getString(Consts.APP_TMP_FOLDER_URL) + "/" + directoryName + "/" + fileName; filePath = settings.getTmpFolderUrl() + "/" + directoryName + "/" + fileName; // Transfer of PUT calls is only allowed if the readOnly flag is // not set. Request contextRequest = new Request(Method.PUT, resourceRef); // Add support of partial PUT calls. contextRequest.getRanges().addAll(getRanges()); contextRequest.setEntity(entity); org.restlet.Response contextResponse = new org.restlet.Response(contextRequest); contextRequest.setResourceRef(resourceRef); getContext().getClientDispatcher().handle(contextRequest, contextResponse); setStatus(contextResponse.getStatus()); } } else { // POST request with no entity. getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST); } return rep; }
From source file:de.jwi.jfm.Folder.java
public void upload(FileItem item, boolean unzip) throws Exception { String name = item.getName(); name = name.replaceAll("\\\\", "/"); int p = name.lastIndexOf('/'); if (p > -1) { name = name.substring(p);/*w w w .ja v a 2 s. c o m*/ } if (unzip) { InputStream is = item.getInputStream(); Unzipper.unzip(is, myFile); } else { File f = new File(myFile, name); item.write(f); } }
From source file:cn.itcast.fredck.FCKeditor.connector.ConnectorServlet.java
/** * Manage the Post requests (FileUpload).<br> * * The servlet accepts commands sent in the following format:<br> * connector?Command=FileUpload&Type=ResourceType&CurrentFolder=FolderPath<br><br> * It store the file (renaming it in case a file with the same name exists) and then return an HTML file * with a javascript command in it.//from www . java 2 s .c om * */ @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (debug) System.out.println("--- BEGIN DOPOST ---"); response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String commandStr = request.getParameter("Command"); String typeStr = request.getParameter("Type"); String currentFolderStr = request.getParameter("CurrentFolder"); String currentPath = baseDir + typeStr + currentFolderStr; String currentDirPath = getServletContext().getRealPath(currentPath); if (debug) System.out.println(currentDirPath); String retVal = "0"; String newName = ""; if (!commandStr.equals("FileUpload")) retVal = "203"; else { DiskFileUpload upload = new DiskFileUpload(); try { List items = upload.parseRequest(request); Map fields = new HashMap(); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) fields.put(item.getFieldName(), item.getString()); else fields.put(item.getFieldName(), item); } FileItem uplFile = (FileItem) fields.get("NewFile"); String fileNameLong = uplFile.getName(); fileNameLong = fileNameLong.replace('\\', '/'); String[] pathParts = fileNameLong.split("/"); String fileName = pathParts[pathParts.length - 1]; String nameWithoutExt = getNameWithoutExtension(fileName); String ext = getExtension(fileName); File pathToSave = new File(currentDirPath, fileName); int counter = 1; while (pathToSave.exists()) { newName = nameWithoutExt + "(" + counter + ")" + "." + ext; retVal = "201"; pathToSave = new File(currentDirPath, newName); counter++; } uplFile.write(pathToSave); } catch (Exception ex) { retVal = "203"; } } out.println("<script type=\"text/javascript\">"); out.println("window.parent.frames['frmUpload'].OnUploadCompleted(" + retVal + ",'" + newName + "');"); out.println("</script>"); out.flush(); out.close(); if (debug) System.out.println("--- END DOPOST ---"); }
From source file:com.primeleaf.krystal.web.action.console.UpdateProfilePictureAction.java
@SuppressWarnings("rawtypes") public WebView execute(HttpServletRequest request, HttpServletResponse response) throws Exception { request.setCharacterEncoding(HTTPConstants.CHARACTER_ENCODING); HttpSession session = request.getSession(); User loggedInUser = (User) session.getAttribute(HTTPConstants.SESSION_KRYSTAL); if (request.getMethod().equalsIgnoreCase("POST")) { try {//from w ww . ja v a 2 s . c om String userName = loggedInUser.getUserName(); String sessionid = (String) session.getId(); String tempFilePath = System.getProperty("java.io.tmpdir"); if (!(tempFilePath.endsWith("/") || tempFilePath.endsWith("\\"))) { tempFilePath += System.getProperty("file.separator"); } tempFilePath += userName + "_" + sessionid; //variables String fileName = "", ext = ""; File file = null; // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); request.setCharacterEncoding(HTTPConstants.CHARACTER_ENCODING); upload.setHeaderEncoding(HTTPConstants.CHARACTER_ENCODING); List listItems = upload.parseRequest((HttpServletRequest) request); Iterator iter = listItems.iterator(); FileItem fileItem = null; while (iter.hasNext()) { fileItem = (FileItem) iter.next(); if (!fileItem.isFormField()) { try { fileName = fileItem.getName(); file = new File(fileName); fileName = file.getName(); ext = fileName.substring(fileName.lastIndexOf(".") + 1).toUpperCase(); if (!"JPEG".equalsIgnoreCase(ext) && !"JPG".equalsIgnoreCase(ext) && !"PNG".equalsIgnoreCase(ext)) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid image. Please upload JPG or PNG file"); return (new MyProfileAction().execute(request, response)); } file = new File(tempFilePath + "." + ext); fileItem.write(file); } catch (Exception ex) { session.setAttribute("UPLOAD_ERROR", ex.getLocalizedMessage()); return (new MyProfileAction().execute(request, response)); } } } //if if (file.length() <= 0) { //code for checking minimum size of file request.setAttribute(HTTPConstants.REQUEST_ERROR, "Zero length document"); return (new MyProfileAction().execute(request, response)); } if (file.length() > (1024 * 1024 * 2)) { //code for checking minimum size of file request.setAttribute(HTTPConstants.REQUEST_ERROR, "Image size too large. Upload upto 2MB file"); return (new MyProfileAction().execute(request, response)); } User user = loggedInUser; user.setProfilePicture(file); UserDAO.getInstance().setProfilePicture(user); AuditLogManager.log(new AuditLogRecord(user.getUserId(), AuditLogRecord.OBJECT_USER, AuditLogRecord.ACTION_EDITED, loggedInUser.getUserName(), request.getRemoteAddr(), AuditLogRecord.LEVEL_INFO, "", "Profile picture update")); } catch (Exception e) { e.printStackTrace(System.out); } } request.setAttribute(HTTPConstants.REQUEST_MESSAGE, "Profile picture uploaded successfully"); return (new MyProfileAction().execute(request, response)); }
From source file:com.fredck.FCKeditor.connector.ConnectorServlet.java
/** * Manage the Post requests (FileUpload).<br> * //from w w w. j av a 2 s . c om * The servlet accepts commands sent in the following format:<br> * connector?Command=FileUpload&Type=ResourceType&CurrentFolder=FolderPath<br> * <br> * It store the file (renaming it in case a file with the same name exists) * and then return an HTML file with a javascript command in it. * */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("ConnectorServlet.doPost"); if (debug) System.out.println("--- BEGIN DOPOST ---"); response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String commandStr = request.getParameter("Command"); String typeStr = request.getParameter("Type"); String currentFolderStr = request.getParameter("CurrentFolder"); String currentPath = baseDir + typeStr + currentFolderStr; String currentDirPath = getServletContext().getRealPath(currentPath); if (debug) System.out.println(currentDirPath); String retVal = "0"; String newName = ""; if (!commandStr.equals("FileUpload")) retVal = "203"; else { DiskFileUpload upload = new DiskFileUpload(); try { List items = upload.parseRequest(request); Map fields = new HashMap(); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) fields.put(item.getFieldName(), item.getString()); else fields.put(item.getFieldName(), item); } FileItem uplFile = (FileItem) fields.get("NewFile"); String fileNameLong = uplFile.getName(); fileNameLong = fileNameLong.replace('\\', '/'); String[] pathParts = fileNameLong.split("/"); String fileName = pathParts[pathParts.length - 1]; String nameWithoutExt = getNameWithoutExtension(fileName); String ext = getExtension(fileName); File pathToSave = new File(currentDirPath, fileName); int counter = 1; while (pathToSave.exists()) { newName = nameWithoutExt + "(" + counter + ")" + "." + ext; retVal = "201"; pathToSave = new File(currentDirPath, newName); counter++; } uplFile.write(pathToSave); } catch (Exception ex) { retVal = "203"; } } System.out.println("1111111111111111111111"); out.println("<script type=\"text/javascript\">"); out.println("window.parent.frames['frmUpload'].OnUploadCompleted(" + retVal + ",'" + newName + "');"); out.println("</script>"); out.flush(); out.close(); if (debug) System.out.println("--- END DOPOST ---"); }
From source file:com.sonicle.webtop.core.app.AbstractEnvironmentService.java
public void processUpload(HttpServletRequest request, HttpServletResponse response, PrintWriter out) { ServletFileUpload upload = null;//from www. j av a 2 s .c o m WebTopSession.UploadedFile uploadedFile = null; HashMap<String, String> multipartParams = new HashMap<>(); try { String service = ServletUtils.getStringParameter(request, "service", true); String cntx = ServletUtils.getStringParameter(request, "context", true); String tag = ServletUtils.getStringParameter(request, "tag", null); if (!ServletFileUpload.isMultipartContent(request)) throw new Exception("No upload request"); IServiceUploadStreamListener istream = getUploadStreamListener(cntx); if (istream != null) { try { MapItem data = new MapItem(); // Empty response data // Defines the upload object upload = new ServletFileUpload(); FileItemIterator it = upload.getItemIterator(request); while (it.hasNext()) { FileItemStream fis = it.next(); if (fis.isFormField()) { InputStream is = null; try { is = fis.openStream(); String key = fis.getFieldName(); String value = IOUtils.toString(is, "UTF-8"); multipartParams.put(key, value); } finally { IOUtils.closeQuietly(is); } } else { // Creates uploaded object uploadedFile = new WebTopSession.UploadedFile(true, service, IdentifierUtils.getUUID(), tag, fis.getName(), -1, findMediaType(fis)); // Fill response data data.add("virtual", uploadedFile.isVirtual()); data.add("editable", isFileEditableInDocEditor(fis.getName())); // Handle listener, its implementation can stop // file upload throwing a UploadException. InputStream is = null; try { getEnv().getSession().addUploadedFile(uploadedFile); is = fis.openStream(); istream.onUpload(cntx, request, multipartParams, uploadedFile, is, data); } finally { IOUtils.closeQuietly(is); getEnv().getSession().removeUploadedFile(uploadedFile, false); } } } new JsonResult(data).printTo(out); } catch (UploadException ex1) { new JsonResult(false, ex1.getMessage()).printTo(out); } catch (Exception ex1) { throw ex1; } } else { try { MapItem data = new MapItem(); // Empty response data IServiceUploadListener iupload = getUploadListener(cntx); // Defines the upload object DiskFileItemFactory factory = new DiskFileItemFactory(); //TODO: valutare come imporre i limiti //factory.setSizeThreshold(yourMaxMemorySize); //factory.setRepository(yourTempDirectory); upload = new ServletFileUpload(factory); List<FileItem> files = upload.parseRequest(request); // Plupload component (client-side) will upload multiple file // each in its own request. So we can skip loop on files. Iterator it = files.iterator(); while (it.hasNext()) { FileItem fi = (FileItem) it.next(); if (fi.isFormField()) { InputStream is = null; try { is = fi.getInputStream(); String key = fi.getFieldName(); String value = IOUtils.toString(is, "UTF-8"); multipartParams.put(key, value); } finally { IOUtils.closeQuietly(is); } } else { // Writes content into a temp file File file = WT.createTempFile(UPLOAD_TEMPFILE_PREFIX); fi.write(file); // Creates uploaded object uploadedFile = new WebTopSession.UploadedFile(false, service, file.getName(), tag, fi.getName(), fi.getSize(), findMediaType(fi)); getEnv().getSession().addUploadedFile(uploadedFile); // Fill response data data.add("virtual", uploadedFile.isVirtual()); data.add("uploadId", uploadedFile.getUploadId()); data.add("editable", isFileEditableInDocEditor(fi.getName())); // Handle listener (if present), its implementation can stop // file upload throwing a UploadException. if (iupload != null) { try { iupload.onUpload(cntx, request, multipartParams, uploadedFile, data); } catch (UploadException ex2) { getEnv().getSession().removeUploadedFile(uploadedFile, true); throw ex2; } } } } new JsonResult(data).printTo(out); } catch (UploadException ex1) { new JsonResult(ex1).printTo(out); } } } catch (Exception ex) { WebTopApp.logger.error("Error uploading", ex); new JsonResult(ex).printTo(out); } }
From source file:hoot.services.ingest.MultipartSerializer.java
protected void _serializeFGDB(List<FileItem> fileItemsList, String jobId, Map<String, String> uploadedFiles, Map<String, String> uploadedFilesPaths) throws Exception { Iterator<FileItem> fileItemsIterator = fileItemsList.iterator(); Map<String, String> folderMap = new HashMap<String, String>(); while (fileItemsIterator.hasNext()) { FileItem fileItem = fileItemsIterator.next(); String fileName = fileItem.getName(); String relPath = FilenameUtils.getPath(fileName); if (relPath.endsWith("/")) { relPath = relPath.substring(0, relPath.length() - 1); }/*w w w . j a v a 2s. c o m*/ fileName = FilenameUtils.getName(fileName); String fgdbFolderPath = homeFolder + "/upload/" + jobId + "/" + relPath; String pathVal = folderMap.get(fgdbFolderPath); if (pathVal == null) { File folderPath = new File(fgdbFolderPath); FileUtils.forceMkdir(folderPath); folderMap.put(fgdbFolderPath, relPath); } if (fileName == null) { ResourceErrorHandler.handleError("A valid file name was not specified.", Status.BAD_REQUEST, log); } String uploadedPath = fgdbFolderPath + "/" + fileName; File file = new File(uploadedPath); fileItem.write(file); } Iterator it = folderMap.entrySet().iterator(); while (it.hasNext()) { String nameOnly = ""; Map.Entry pairs = (Map.Entry) it.next(); String fgdbName = pairs.getValue().toString(); String[] nParts = fgdbName.split("\\."); for (int i = 0; i < nParts.length - 1; i++) { if (nameOnly.length() > 0) { nameOnly += "."; } nameOnly += nParts[i]; } uploadedFiles.put(nameOnly, "GDB"); uploadedFilesPaths.put(nameOnly, fgdbName); } }