List of usage examples for org.apache.commons.fileupload FileItem write
void write(File file) throws Exception;
From source file:de.betterform.agent.web.servlet.HttpRequestHandler.java
protected void processUploadParameters(Map uploads, HttpServletRequest request) throws XFormsException { if (LOGGER.isDebugEnabled()) { LOGGER.debug("updating " + uploads.keySet().size() + " uploads(s)"); }/* w w w. ja v a2 s. com*/ try { // update repeat indices Iterator iterator = uploads.keySet().iterator(); String id; FileItem item; byte[] data; while (iterator.hasNext()) { id = (String) iterator.next(); item = (FileItem) uploads.get(id); if (item.getSize() > 0) { LOGGER.debug("i'm here"); if (this.xformsProcessor.isFileUpload(id, "anyURI")) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("found upload type 'anyURI'"); } String localPath = new StringBuffer().append(System.currentTimeMillis()).append('/') .append(item.getName()).toString(); File localFile = new File(this.uploadRoot, localPath); localFile.getParentFile().mkdirs(); item.write(localFile); if (LOGGER.isDebugEnabled()) { LOGGER.debug("saving data to path: " + localFile); } // todo: externalize file handling and uri generation File uploadDir = new File(request.getContextPath(), Config.getInstance().getProperty(WebFactory.UPLOADDIR_PROPERTY)); String urlEncodedPath = URLEncoder .encode(new File(uploadDir.getPath(), localPath).getPath(), "UTF-8"); URI uploadTargetDir = new URI(urlEncodedPath); data = uploadTargetDir.toString().getBytes(); } else { data = item.get(); } this.xformsProcessor.setUploadValue(id, item.getContentType(), item.getName(), data); // After the value has been set and the RRR took place, create new UploadInfo with status set to 'done' request.getSession().setAttribute(WebProcessor.ADAPTER_PREFIX + sessionKey + "-uploadInfo", new UploadInfo(1, 0, 0, 0, "done")); } else { if (LOGGER.isDebugEnabled()) { LOGGER.debug("ignoring empty upload " + id); } // todo: removal ? } item.delete(); } } catch (Exception e) { throw new XFormsException(e); } }
From source file:com.meikai.common.web.servlet.FCKeditorUploadServlet.java
/** * Manage the Upload requests.<br> * * The servlet accepts commands sent in the following format:<br> * simpleUploader?Type=ResourceType<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 ww w .j a v a2 s. c om * */ 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(); // edit check user uploader file size int contextLength = request.getContentLength(); int fileSize = (int) (((float) contextLength) / ((float) (1024))); String retVal = "0"; String newName = ""; String fileUrl = ""; String errorMessage = ""; if (fileSize < 30240) { String typeStr = request.getParameter("Type"); String currentPath = ""; String currentDirPath = getServletContext().getRealPath(currentPath); currentPath = request.getContextPath() + currentPath; // edit end ++++++++++++++++ if (debug) System.out.println(currentDirPath); if (enabled) { 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 = FckeditorUtil.getNameWithoutExtension(fileName); String ext = FckeditorUtil.getExtension(fileName); File pathToSave = new File(currentDirPath, fileName); fileUrl = currentPath + "/" + fileName; if (FckeditorUtil.extIsAllowed(allowedExtensions, deniedExtensions, typeStr, ext)) { int counter = 1; while (pathToSave.exists()) { newName = nameWithoutExt + "(" + counter + ")" + "." + ext; fileUrl = currentPath + "/" + newName; retVal = "201"; pathToSave = new File(currentDirPath, newName); counter++; } uplFile.write(pathToSave); // ? if (logger.isInfoEnabled()) { logger.info("..."); } } else { retVal = "202"; errorMessage = ""; if (debug) System.out.println("Invalid file type: " + ext); } } catch (Exception ex) { if (debug) ex.printStackTrace(); retVal = "203"; } } else { retVal = "1"; errorMessage = "This file uploader is disabled. Please check the WEB-INF/web.xml file"; } } else { retVal = "204"; } out.println("<script type=\"text/javascript\">"); out.println("window.parent.OnUploadCompleted(" + retVal + ",'" + fileUrl + "','" + newName + "','" + errorMessage + "');"); out.println("</script>"); out.flush(); out.close(); if (debug) System.out.println("--- END DOPOST ---"); }
From source file:cdc.util.Upload.java
public boolean anexos(HttpServletRequest request, HttpServletResponse response) throws Exception { if (ServletFileUpload.isMultipartContent(request)) { int cont = 0; ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory()); List fileItemsList = null; try {/* w w w . j av a 2 s . c o m*/ fileItemsList = servletFileUpload.parseRequest(request); } catch (FileUploadException e) { e.printStackTrace(); } String optionalFileName = ""; FileItem fileItem = null; Iterator it = fileItemsList.iterator(); do { //cont++; FileItem fileItemTemp = (FileItem) it.next(); if (fileItemTemp.isFormField()) { if (fileItemTemp.getFieldName().equals("file")) { optionalFileName = fileItemTemp.getString(); } } else { fileItem = fileItemTemp; } if (cont != (fileItemsList.size())) { if (fileItem != null) { String fileName = fileItem.getName(); if (fileItem.getSize() > 0) { if (optionalFileName.trim().equals("")) { fileName = FilenameUtils.getName(fileName); } else { fileName = optionalFileName; } String dirName = request.getServletContext().getRealPath(pasta); File saveTo = new File(dirName + fileName); //System.out.println("caminho: " + saveTo.toString() ); try { fileItem.write(saveTo); } catch (Exception e) { } } } } cont++; } while (it.hasNext()); return true; } else { return false; } }
From source file:hu.sztaki.lpds.pgportal.portlets.credential.MyProxyPortlet.java
/** * Checks if the SAML file exists in the user's directory. Proper messages * are sent to the GUI.//from www . java 2 s .c om * @param ActionRequest * @param samlfile FileItem the SAML Asertion * @param usrId String containing the user id * @throws Exception */ private void uploadSaml(ActionRequest request, FileItem samlfile, String usrId) throws Exception { FileItem sf = samlfile; String userId = usrId; try { if (checkFile(request, "SAML", samlfile)) { String usrDir = this.loadUsersDirPath() + "/" + userId + "/" + "x509up.assertion"; File saveTo = new File(usrDir); sf.write(saveTo); request.setAttribute("msg", "Upload successful."); //response.setRenderParameter("nextJSP","credentialList.jsp"); } } catch (Exception e) { request.setAttribute("msg", "Upload failed! Reason: " + e.getMessage()); //response.setRenderParameter("nextJSP",""credentialList.jsp"; e.printStackTrace(); } }
From source file:com.krawler.esp.servlets.importICSServlet.java
private File getfile(HttpServletRequest request) { DiskFileUpload fu = new DiskFileUpload(); String Ext = null;//from w w w . ja v a 2 s . co m File uploadFile = null; List fileItems = null; try { fileItems = fu.parseRequest(request); } catch (FileUploadException e) { KrawlerLog.op.warn("Problem While Uploading file :" + e.toString()); } for (Iterator i = fileItems.iterator(); i.hasNext();) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { String fileName = null; try { fileName = new String(fi.getName().getBytes(), "UTF8"); if (fileName.contains(".")) { Ext = fileName.substring(fileName.lastIndexOf(".")); } if (fi.getSize() != 0) { uploadFile = File.createTempFile("iCalDeskeraTemp", ".ics"); fi.write(uploadFile); } } catch (Exception e) { KrawlerLog.op.warn("Problem While Reading file :" + e.toString()); } } else { arrParam.put(fi.getFieldName(), fi.getString()); } } return uploadFile; }
From source file:edu.cornell.mannlib.vitro.webapp.controller.harvester.FileHarvestController.java
/** * This is for when the user clicks the "Upload" button on the form, sending a file to the server. An HTTP post is * redirected here when it is determined that the request was multipart (as this will identify the post as a file * upload click).// w w w.j av a 2 s . c o m * @param request the HTTP request * @param response the HTTP response * @throws IOException if an IO error occurs * @throws ServletException if a servlet error occurs */ private void doFileUploadPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { JSONObject json = generateJson(false); try { VitroRequest vreq = new VitroRequest(request); //parse request for uploaded file int maxFileSize = 1024 * 1024; FileUploadServletRequest req = FileUploadServletRequest.parseRequest(vreq, maxFileSize); if (req.hasFileUploadException()) { Exception e = req.getFileUploadException(); new ExceptionVisibleToUser(e); } //get the job parameter String jobParameter = req.getParameter(PARAMETER_JOB); //get the location where we want to save the files (it will end in a slash), then create a File object out of it String path = getUploadPath(vreq); File directory = new File(path); //if this is a page refresh, we do not want to save stale files that the user doesn't want anymore, but we // still have the same session ID and therefore the upload directory is unchanged. Thus we must clear the // upload directory if it exists (a "first upload" parameter, initialized to "true" but which gets set to // "false" once the user starts uploading stuff is used for this). String firstUpload = req.getParameter(PARAMETER_FIRST_UPLOAD); //clear directory on first upload if (firstUpload.toLowerCase().equals("true")) { if (directory.exists()) { File[] children = directory.listFiles(); for (File child : children) { child.delete(); } } } //if the upload directory does not exist then create it if (!directory.exists()) directory.mkdirs(); //get the file harvest job for this request (this will determine what type of harvest is run) FileHarvestJob job = getJob(vreq, jobParameter); //get the files out of the parsed request (there should only be one) Map<String, List<FileItem>> fileStreams = req.getFiles(); if (fileStreams.get(PARAMETER_UPLOADED_FILE) != null && fileStreams.get(PARAMETER_UPLOADED_FILE).size() > 0) { //get the individual file data from the request FileItem csvStream = fileStreams.get(PARAMETER_UPLOADED_FILE).get(0); String name = csvStream.getName(); //if another uploaded file exists with the same name, alter the name so that it is unique name = handleNameCollision(name, directory); //write the file from the request to the upload directory File file = new File(path + name); try { csvStream.write(file); } finally { csvStream.delete(); } //ask the file harvest job to validate that it's okay with what was uploaded; if not delete the file String errorMessage = job.validateUpload(file); boolean success; if (errorMessage != null) { success = false; file.delete(); } else { success = true; errorMessage = "success"; } //prepare the results which will be sent back to the browser for display try { json.put("success", success); json.put("fileName", name); json.put("errorMessage", errorMessage); } catch (JSONException e) { log.error(e, e); return; } } else { //if for some reason no file was included with the request, send an error back try { json.put("success", false); json.put("fileName", "(none)"); json.put("errorMessage", "No file uploaded"); } catch (JSONException e) { log.error(e, e); return; } } } catch (ExceptionVisibleToUser e) { log.error(e, e); //handle exceptions whose message is for the user try { json.put("success", false); json.put("filename", "(none)"); json.put("errorMessage", e.getMessage()); } catch (JSONException f) { log.error(f, f); return; } } catch (Exception e) { log.error(e, e); json = generateJson(true); } //write the prepared response response.getWriter().write(json.toString()); }
From source file:DatasetUpload.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//w w w.j a va 2 s .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 { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { //process only if its multipart content if (ServletFileUpload.isMultipartContent(request)) { try { List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()) .parseRequest(request); String DatasetName = ""; for (FileItem item : multiparts) { if (!item.isFormField()) { DatasetName = new File(item.getName()).getName(); //write the file to disk // item.write(new File(datasetFolder + File.separator + name)); //System.out.println("File name is :: " + name); // out.print("Upload successeful"); } } DatasetName = DatasetName.substring(0, DatasetName.indexOf(".")); // System.out.println(DatasetName + "*****"); String datasetFolderPath = getServletContext() .getRealPath("datasets" + File.separator + DatasetName); File datasetFolder = new File(datasetFolderPath); //create the folder if it does not exist if (!datasetFolder.exists()) { datasetFolder.mkdir(); } for (FileItem item : multiparts) { if (!item.isFormField()) { String name = new File(item.getName()).getName(); //write the file to disk item.write(new File(datasetFolder + File.separator + name)); //System.out.println("File name is :: " + name); out.print("Upload successeful"); } } } catch (Exception ex) { out.print("File Upload Failed due to " + ex); } } else { out.print("The request did not include any file"); } } catch (Exception ex) { ex.printStackTrace(); } finally { out.close(); } }
From source file:com.silverpeas.silvercrawler.control.SilverCrawlerSessionController.java
public void saveFile(FileItem fileItem, boolean replaceFile) throws SilverCrawlerFileUploadException { String name = FileUtil.getFilename(fileItem.getName()); if (StringUtil.isDefined(name)) { // compute full path String fullPath = getFullPath(name); File newFile = new File(fullPath); // Checks if file already exists if (newFile.exists() && !replaceFile) { throw new SilverCrawlerFileUploadException("SilverCrawlerSessionController.saveFile", SilverpeasException.ERROR, getString("silverCrawler.fileAlreadyExists")); }/* w w w. j av a2 s . c om*/ // Write file to disk try { fileItem.write(newFile); } catch (Exception e) { throw new SilverCrawlerFileUploadException("SilverCrawlerSessionController.saveFile", SilverpeasException.ERROR, getString("silverCrawler.unknownCause"), e); } } }
From source file:com.truthbean.core.web.kindeditor.FileUpload.java
@Override public void service(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { final PageContext pageContext; HttpSession session = null;/*from w ww .ja va 2s .co m*/ final ServletContext application; final ServletConfig config; JspWriter out = null; final Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { response.setContentType("text/html; charset=UTF-8"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; out.write("\r\n"); out.write("\r\n"); out.write("\r\n"); out.write("\r\n"); out.write("\r\n"); out.write("\r\n"); out.write("\r\n"); /** * KindEditor JSP * * JSP???? ?? * */ // ? String savePath = pageContext.getServletContext().getRealPath("/") + "resource/"; String savePath$ = savePath; // ?URL String saveUrl = request.getContextPath() + "/resource/"; // ??? HashMap<String, String> extMap = new HashMap<>(); extMap.put("image", "gif,jpg,jpeg,png,bmp"); extMap.put("flash", "swf,flv"); extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb"); extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2"); // ? long maxSize = 10 * 1024 * 1024 * 1024L; response.setContentType("text/html; charset=UTF-8"); if (!ServletFileUpload.isMultipartContent(request)) { out.println(getError("")); return; } // File uploadDir = new File(savePath); if (!uploadDir.isDirectory()) { out.println(getError("?")); return; } // ?? if (!uploadDir.canWrite()) { out.println(getError("??")); return; } String dirName = request.getParameter("dir"); if (dirName == null) { dirName = "image"; } if (!extMap.containsKey(dirName)) { out.println(getError("???")); return; } // savePath += dirName + "/"; saveUrl += dirName + "/"; File saveDirFile = new File(savePath); if (!saveDirFile.exists()) { saveDirFile.mkdirs(); } SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String ymd = sdf.format(new Date()); savePath += ymd + "/"; saveUrl += ymd + "/"; File dirFile = new File(savePath); if (!dirFile.exists()) { dirFile.mkdirs(); } FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); List items = upload.parseRequest(request); Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); String fileName = item.getName(); if (!item.isFormField()) { // ? if (item.getSize() > maxSize) { out.println(getError("??")); return; } // ?? String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(); if (!Arrays.asList(extMap.get(dirName).split(",")).contains(fileExt)) { out.println(getError("??????\n??" + extMap.get(dirName) + "?")); return; } SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt; try { File uploadedFile = new File(savePath, newFileName); item.write(uploadedFile); } catch (Exception e) { out.println(getError("")); return; } JSONObject obj = new JSONObject(); obj.put("error", 0); obj.put("url", saveUrl + newFileName); request.getSession().setAttribute("fileName", savePath$ + fileName); request.getSession().setAttribute("filePath", savePath + newFileName); request.getSession().setAttribute("fileUrl", saveUrl + newFileName); out.println(obj.toJSONString()); } } out.write('\r'); out.write('\n'); } catch (IOException | FileUploadException t) { if (!(t instanceof javax.servlet.jsp.SkipPageException)) { out = _jspx_out; if (out != null && out.getBufferSize() != 0) { if (response.isCommitted()) { out.flush(); } else { out.clearBuffer(); } } if (_jspx_page_context != null) { _jspx_page_context.handlePageException(t); } else { throw new ServletException(t); } } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } }
From source file:fr.insalyon.creatis.vip.datamanager.server.rpc.FileUploadServiceImpl.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { User user = (User) request.getSession().getAttribute(CoreConstants.SESSION_USER); if (user != null && ServletFileUpload.isMultipartContent(request)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try {//ww w . jav a 2 s. co m List items = upload.parseRequest(request); Iterator iter = items.iterator(); String fileName = null; FileItem fileItem = null; String path = null; String target = "uploadComplete"; String operationID = "no-id"; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.getFieldName().equals("path")) { path = item.getString(); } else if (item.getFieldName().equals("file")) { fileName = item.getName(); fileItem = item; } else if (item.getFieldName().equals("target")) { target = item.getString(); } } if (fileName != null && !fileName.equals("")) { boolean local = path.equals("local") ? true : false; String rootDirectory = DataManagerUtil.getUploadRootDirectory(local); fileName = new File(fileName).getName().trim().replaceAll(" ", "_"); fileName = Normalizer.normalize(fileName, Normalizer.Form.NFD) .replaceAll("\\p{InCombiningDiacriticalMarks}+", ""); File uploadedFile = new File(rootDirectory + fileName); try { fileItem.write(uploadedFile); response.getWriter().write(fileName); if (!local) { // GRIDA Pool Client logger.info("(" + user.getEmail() + ") Uploading '" + uploadedFile.getAbsolutePath() + "' to '" + path + "'."); GRIDAPoolClient client = CoreUtil.getGRIDAPoolClient(); operationID = client.uploadFile(uploadedFile.getAbsolutePath(), DataManagerUtil.parseBaseDir(user, path), user.getEmail()); } else { operationID = fileName; logger.info( "(" + user.getEmail() + ") Uploaded '" + uploadedFile.getAbsolutePath() + "'."); } } catch (Exception ex) { logger.error(ex); } } response.setContentType("text/html"); response.setHeader("Pragma", "No-cache"); response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<script type=\"text/javascript\">"); out.println("if (parent." + target + ") parent." + target + "('" + operationID + "');"); out.println("</script>"); out.println("</body>"); out.println("</html>"); out.flush(); } catch (FileUploadException ex) { logger.error(ex); } } }