List of usage examples for org.apache.commons.fileupload FileItem write
void write(File file) throws Exception;
From source file:edu.harvard.hul.ois.fits.service.servlets.FitsServlet.java
/** * Handles the file upload for FITS processing via streaming of the file using the * <code>POST</code> method. * Example: curl -X POST -F datafile=@<path/to/file> <host>:[<port>]/fits/examine * Note: "fits" in the above URL needs to be adjusted to the final name of the WAR file. * * @param request servlet request/*from w w w. java2 s. c o m*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.debug("Entering doPost()"); if (!ServletFileUpload.isMultipartContent(request)) { ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_BAD_REQUEST, "Missing multipart POST form data.", request.getRequestURL().toString()); sendErrorMessageResponse(errorMessage, response); return; } // configures upload settings DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold((maxInMemoryFileSizeMb * (int) MB_MULTIPLIER)); String tempDir = System.getProperty("java.io.tmpdir"); logger.debug("Creating temp directory for storing uploaded files: " + tempDir); factory.setRepository(new File(tempDir)); ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(maxFileUploadSizeMb * MB_MULTIPLIER); upload.setSizeMax(maxRequestSizeMb * MB_MULTIPLIER); try { List<FileItem> formItems = upload.parseRequest(request); Iterator<FileItem> iter = formItems.iterator(); Map<String, String[]> paramMap = request.getParameterMap(); boolean includeStdMetadata = true; String[] vals = paramMap.get(Constants.INCLUDE_STANDARD_OUTPUT_PARAM); if (vals != null && vals.length > 0) { if (FALSE.equalsIgnoreCase(vals[0])) { includeStdMetadata = false; logger.debug("flag includeStdMetadata set to : " + includeStdMetadata); } } // file-specific directory path to store uploaded file // ensures unique sub-directory to handle rare case of duplicate file name String subDir = String.valueOf((new Date()).getTime()); String uploadPath = uploadBaseDir + File.separator + subDir; File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdir(); } // iterates over form's fields -- should only be one for uploaded file while (iter.hasNext()) { FileItem item = iter.next(); if (!item.isFormField() && item.getFieldName().equals(FITS_FORM_FIELD_DATAFILE)) { String fileName = item.getName(); if (StringUtils.isEmpty(fileName)) { ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_BAD_REQUEST, "Missing File Data.", request.getRequestURL().toString()); sendErrorMessageResponse(errorMessage, response); return; } // ensure a unique local fine name String fileNameAndPath = uploadPath + File.separator + item.getName(); File storeFile = new File(fileNameAndPath); item.write(storeFile); // saves the file on disk if (!storeFile.exists()) { ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Uploaded file does not exist.", request.getRequestURL().toString()); sendErrorMessageResponse(errorMessage, response); return; } // Send it to the FITS processor... try { sendFitsExamineResponse(storeFile.getAbsolutePath(), includeStdMetadata, request, response); } catch (Exception e) { logger.error("Unexpected exception: " + e.getMessage(), e); ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage(), request.getRequestURL().toString()); sendErrorMessageResponse(errorMessage, response); return; } finally { // delete the uploaded file if (storeFile.delete()) { logger.debug(storeFile.getName() + " is deleted!"); } else { logger.warn(storeFile.getName() + " could not be deleted!"); } if (uploadDir.delete()) { logger.debug(uploadDir.getName() + " is deleted!"); } else { logger.warn(uploadDir.getName() + " could not be deleted!"); } } } else { ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_BAD_REQUEST, "The request did not have the correct name attribute of \"datafile\" in the form processing. ", request.getRequestURL().toString(), "Processing halted."); sendErrorMessageResponse(errorMessage, response); return; } } } catch (Exception ex) { logger.error("Unexpected exception: " + ex.getMessage(), ex); ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage(), request.getRequestURL().toString(), "Processing halted."); sendErrorMessageResponse(errorMessage, response); return; } }
From source file:kreidos.diamond.web.action.console.NewDocumentAction.java
@SuppressWarnings("rawtypes") public WebView execute(HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); User loggedInUser = (User) session.getAttribute(HTTPConstants.SESSION_KRYSTAL); String classId = request.getParameter("classid") != null ? request.getParameter("classid") : "0"; if (request.getMethod().equalsIgnoreCase("POST")) { try {/*from w ww . j a va2s . co m*/ String userName = loggedInUser.getUserName(); String tempFilePath = System.getProperty("java.io.tmpdir"); if (!(tempFilePath.endsWith("/") || tempFilePath.endsWith("\\"))) { tempFilePath += System.getProperty("file.separator"); } //variables String fileName = "", comments = ""; 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); upload.setHeaderEncoding(HTTPConstants.CHARACTER_ENCODING); //Create a file upload progress listener FileUploadProgressListener listener = new FileUploadProgressListener(); upload.setProgressListener(listener); //put the listener in session session.setAttribute("LISTENER", listener); session.setAttribute("UPLOAD_ERROR", null); session.setAttribute("UPLOAD_PERCENT_COMPLETE", new Long(0)); DocumentClass documentClass = null; Hashtable<String, String> indexRecord = new Hashtable<String, String>(); String name = ""; String value = ""; List listItems = upload.parseRequest((HttpServletRequest) request); Iterator iter = listItems.iterator(); FileItem fileItem = null; while (iter.hasNext()) { fileItem = (FileItem) iter.next(); if (fileItem.isFormField()) { name = fileItem.getFieldName(); value = fileItem.getString(HTTPConstants.CHARACTER_ENCODING); if (name.equals("classid")) { classId = value; } if (name.equals("txtNote")) { comments = value; } } else { try { fileName = fileItem.getName(); file = new File(fileName); fileName = file.getName(); file = new File(tempFilePath + fileName); fileItem.write(file); } catch (Exception ex) { session.setAttribute("UPLOAD_ERROR", ex.getLocalizedMessage()); return null; } } } //if if (file.length() <= 0) { //code for checking minimum size of file session.setAttribute("UPLOAD_ERROR", "Zero length document"); return null; } documentClass = DocumentClassDAO.getInstance().readDocumentClassById(Integer.parseInt(classId)); if (documentClass == null) { session.setAttribute("UPLOAD_ERROR", "Invalid document class"); return null; } AccessControlManager aclManager = new AccessControlManager(); ACL acl = aclManager.getACL(documentClass, loggedInUser); if (!acl.canCreate()) { session.setAttribute("UPLOAD_ERROR", "Access Denied"); return null; } String indexValue = ""; String indexName = ""; session.setAttribute("UPLOAD_PERCENT_COMPLETE", new Long(50)); for (IndexDefinition indexDefinition : documentClass.getIndexDefinitions()) { indexName = indexDefinition.getIndexColumnName(); Iterator iter1 = listItems.iterator(); while (iter1.hasNext()) { FileItem item1 = (FileItem) iter1.next(); if (item1.isFormField()) { name = item1.getFieldName(); value = item1.getString(HTTPConstants.CHARACTER_ENCODING); if (name.equals(indexName)) { indexValue = value; String errorMessage = ""; if (indexValue != null) { if (indexDefinition.isMandatory()) { if (indexValue.trim().length() <= 0) { errorMessage = "Invalid input for " + indexDefinition.getIndexDisplayName(); session.setAttribute("UPLOAD_ERROR", errorMessage); return null; } } if (IndexDefinition.INDEXTYPE_NUMBER .equalsIgnoreCase(indexDefinition.getIndexType())) { if (indexValue.trim().length() > 0) { if (!GenericValidator.matchRegexp(indexValue, HTTPConstants.NUMERIC_REGEXP)) { errorMessage = "Invalid input for " + indexDefinition.getIndexDisplayName(); session.setAttribute("UPLOAD_ERROR", errorMessage); return null; } } } else if (IndexDefinition.INDEXTYPE_DATE .equalsIgnoreCase(indexDefinition.getIndexType())) { if (indexValue.trim().length() > 0) { if (!GenericValidator.isDate(indexValue, "yyyy-MM-dd", true)) { errorMessage = "Invalid input for " + indexDefinition.getIndexDisplayName(); session.setAttribute("UPLOAD_ERROR", errorMessage); return null; } } } if (indexValue.trim().length() > indexDefinition.getIndexMaxLength()) { //code for checking index field length errorMessage = "Document index size exceeded for " + "Index Name : " + indexDefinition.getIndexDisplayName() + " [ " + "Index Length : " + indexDefinition.getIndexMaxLength() + " , " + "Actual Length : " + indexValue.length() + " ]"; session.setAttribute("UPLOAD_ERROR", errorMessage); return null; } } indexRecord.put(indexName, indexValue); } } } //while iter } //while indexCfgList session.setAttribute("UPLOAD_PERCENT_COMPLETE", new Long(70)); DocumentRevision documentRevision = new DocumentRevision(); documentRevision.setClassId(documentClass.getClassId()); documentRevision.setDocumentId(0); documentRevision.setRevisionId("1.0"); documentRevision.setDocumentFile(file); documentRevision.setUserName(loggedInUser.getUserName()); documentRevision.setIndexRecord(indexRecord); documentRevision.setComments(comments); DocumentManager documentManager = new DocumentManager(); documentManager.storeDocument(documentRevision, documentClass); //Log the entry to audit logs AuditLogManager.log(new AuditLogRecord(documentRevision.getDocumentId(), AuditLogRecord.OBJECT_DOCUMENT, AuditLogRecord.ACTION_CREATED, userName, request.getRemoteAddr(), AuditLogRecord.LEVEL_INFO, "", "Document created")); session.setAttribute("UPLOAD_PERCENT_COMPLETE", new Long(100)); } catch (Exception e) { e.printStackTrace(System.out); } return null; } else { try { ArrayList<DocumentClass> availableDocumentClasses = DocumentClassDAO.getInstance() .readDocumentClasses(" ACTIVE = 'Y'"); ArrayList<DocumentClass> documentClasses = new ArrayList<DocumentClass>(); AccessControlManager aclManager = new AccessControlManager(); for (DocumentClass documentClass : availableDocumentClasses) { ACL acl = aclManager.getACL(documentClass, loggedInUser); if (acl.canCreate()) { documentClasses.add(documentClass); } } int documentClassId = 0; try { documentClassId = Integer.parseInt(classId); } catch (Exception ex) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid input"); return (new NewDocumentView(request, response)); } if (documentClassId > 0) { DocumentClass selectedDocumentClass = DocumentClassDAO.getInstance() .readDocumentClassById(documentClassId); request.setAttribute("DOCUMENTCLASS", selectedDocumentClass); } request.setAttribute("CLASSID", documentClassId); request.setAttribute("CLASSLIST", documentClasses); } catch (Exception ex) { ex.printStackTrace(); } } return (new NewDocumentView(request, response)); }
From source file:com.krawler.esp.servlets.ExportImportContactsServlet.java
private File getfile(HttpServletRequest request) { DiskFileUpload fu = new DiskFileUpload(); String Ext = null;/* w w w . j ava2 s .c o 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("contacts", ".csv"); 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:com.krawler.esp.servlets.FileImporterServlet.java
public File getfile(HttpServletRequest request, String fileid) throws ServiceException { File uploadFile = null;/*from w w w .j a v a 2s.c o m*/ try { String destinationDirectory = StorageHandler.GetDocStorePath() + StorageHandler.GetFileSeparator() + "importplans"; File destdir = new File(destinationDirectory); if (!destdir.exists()) { destdir.mkdir(); } DiskFileUpload fu = new DiskFileUpload(); String Ext = ""; 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(".")); } long size = fi.getSize(); if (fi.getSize() != 0) { String projid = request.getParameter("projectid"); uploadFile = new File( destinationDirectory + StorageHandler.GetFileSeparator() + fileid + Ext); fi.write(uploadFile); fildoc(fileid, fileName, projid, fileid + Ext, AuthHandler.getUserid(request), size); } } catch (IOException ex) { KrawlerLog.op.warn("Problem While Reading file :" + ex.toString()); throw ServiceException.FAILURE("FileImporterServlet.getfile", ex); } catch (ServiceException ex) { KrawlerLog.op.warn("Problem While Reading file :" + ex); throw ServiceException.FAILURE("FileImporterServlet.getfile", ex); } catch (Exception ex) { KrawlerLog.op.warn("Problem While Reading file :" + ex.toString()); throw ServiceException.FAILURE("FileImporterServlet.getfile", ex); } } else { arrParam.put(fi.getFieldName(), fi.getString()); } } } catch (ConfigurationException ex) { KrawlerLog.op.warn("Problem Storing Data In DB [FileImporterServlet.storeInDB()]:" + ex); throw ServiceException.FAILURE("FileImporterServlet.getfile", ex); } return uploadFile; }
From source file:it.eng.spagobi.engines.talend.services.JobUploadService.java
private String[] processUploadedFile(FileItem item, JobDeploymentDescriptor jobDeploymentDescriptor) throws ZipException, IOException, SpagoBIEngineException { String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); if (fieldName.equalsIgnoreCase("deploymentDescriptor")) return null; RuntimeRepository runtimeRepository = TalendEngine.getRuntimeRepository(); File jobsDir = new File(runtimeRepository.getRootDir(), jobDeploymentDescriptor.getLanguage().toLowerCase()); File projectDir = new File(jobsDir, jobDeploymentDescriptor.getProject()); File tmpDir = new File(projectDir, "tmp"); if (!tmpDir.exists()) tmpDir.mkdirs();/*www . j a v a2 s. co m*/ File uploadedFile = new File(tmpDir, fileName); try { item.write(uploadedFile); } catch (Exception e) { e.printStackTrace(); } String[] dirNames = ZipUtils.getDirectoryNameByLevel(new ZipFile(uploadedFile), 2); List dirNameList = new ArrayList(); for (int i = 0; i < dirNames.length; i++) { if (!dirNames[i].equalsIgnoreCase("lib")) dirNameList.add(dirNames[i]); } String[] jobNames = (String[]) dirNameList.toArray(new String[0]); runtimeRepository.deployJob(jobDeploymentDescriptor, new ZipFile(uploadedFile)); uploadedFile.delete(); tmpDir.delete(); return jobNames; }
From source file:com.chrischurchwell.jukeit.server.ServerHandler.java
@Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Debug.debug("Handling Web Request: ", target); if (target.equalsIgnoreCase("/")) { response.setContentType("text/html;charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); baseRequest.setHandled(true);//from w ww .j a v a 2s . c o m Template template = cfg.getTemplate("index.html"); Map<String, Object> dataRoot = new HashMap<String, Object>(); dataRoot.put("serverName", JukeIt.getInstance().getConfig().getString("serverName")); dataRoot.put("allowUpload", JukeIt.getInstance().getConfig().getBoolean("allowWebServerUploads")); dataRoot.put("files", JukeIt.getServerFileList()); try { template.process(dataRoot, response.getWriter()); } catch (TemplateException e) { // TODO Auto-generated catch block e.printStackTrace(); } return; } if (target.equalsIgnoreCase("/robots.txt")) { response.setContentType("text/plain;charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); baseRequest.setHandled(true); response.getWriter().println("User-agent: *"); response.getWriter().println("Disallow: /"); return; } if (target.equalsIgnoreCase("/upload")) { if (!JukeIt.getInstance().getConfig().getBoolean("allowWebServerUploads")) { return; } response.setContentType("text/html;charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); baseRequest.setHandled(true); if (!ServletFileUpload.isMultipartContent(request)) { response.getWriter().println("No File Upload Detected"); return; } /* Straight from commons.io docs */ // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request try { List<FileItem> items = castList(FileItem.class, upload.parseRequest(request)); // Process the uploaded items Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { //processFormField(item); } else { //processUploadedFile(item); //String fieldName = item.getFieldName(); //String fileName = item.getName(); //String contentType = item.getContentType(); //boolean isInMemory = item.isInMemory(); //long sizeInBytes = item.getSize(); if (!item.getName().endsWith(".ogg") && !item.getName().endsWith(".wav") && !item.getName().endsWith(".mp3")) { response.getWriter().println("File must be a .ogg or .wave"); return; } String name = item.getName().replace(" ", "_"); File uploadedFile = new File(JukeIt.getInstance().getDataFolder(), "music/" + name); item.write(uploadedFile); response.getWriter().println("1"); return; } } } catch (FileUploadException e) { response.getWriter().println(e.getMessage()); return; } catch (Exception e) { response.getWriter().println(e.getMessage()); return; } return; } }
From source file:cn.itcast.fredck.FCKeditor.uploader.SimpleUploaderServlet.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 w ww. jav a 2 s . c o m*/ * */ @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 typeStr = request.getParameter("Type"); String currentPath = baseDir + typeStr; String currentDirPath = getServletContext().getRealPath(currentPath); currentPath = request.getContextPath() + currentPath; if (debug) System.out.println(currentDirPath); String retVal = "0"; String newName = ""; String fileUrl = ""; String errorMessage = ""; 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 = getNameWithoutExtension(fileName); String ext = getExtension(fileName); File pathToSave = new File(currentDirPath, fileName); fileUrl = currentPath + "/" + fileName; if (extIsAllowed(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); } 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"; } 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:com.glaf.base.utils.upload.FileUploadBackGroundServlet.java
/** * ?/*from w w w .ja va2 s.c om*/ */ private void processFileUpload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String serviceKey = request.getParameter("serviceKey"); if (serviceKey == null) { serviceKey = "global"; } int maxUploadSize = conf.getInt(serviceKey + ".maxUploadSize", 0); if (maxUploadSize == 0) { maxUploadSize = conf.getInt("upload.maxUploadSize", 10);// 10MB } maxUploadSize = maxUploadSize * FileUtils.MB_SIZE; DiskFileItemFactory factory = new DiskFileItemFactory(); // ? factory.setSizeThreshold(204800); File tempDir = new File(getUploadDir() + "/temp"); if (!tempDir.exists()) { tempDir.mkdir(); } // ? factory.setRepository(tempDir); ServletFileUpload upload = new ServletFileUpload(factory); // ? upload.setFileSizeMax(maxUploadSize); // request upload.setSizeMax(maxUploadSize); upload.setProgressListener(new FileUploadListener(request)); upload.setHeaderEncoding("UTF-8"); // ???FileUploadStatus Bean FileMgmtFactory.saveStatusBean(request, initStatusBean(request)); try { List<?> items = upload.parseRequest(request); // url for (int i = 0; i < items.size(); i++) { FileItem item = (FileItem) items.get(i); if (item.isFormField()) { break; } } // String uploadDir = com.glaf.base.utils.StringUtil.createDir(getUploadDir()); // ? for (int i = 0; i < items.size(); i++) { FileItem item = (FileItem) items.get(i); // ? if (FileMgmtFactory.getStatusBean(request).getCancel()) { deleteUploadedFile(request); break; } else if (!item.isFormField() && item.getName().length() > 0) { logger.debug("" + item.getName()); // ? String fileId = UUID32.getUUID(); String path = uploadDir + FileUtils.sp + fileId; File uploadedFile = new File(new File(getUploadDir(), uploadDir), fileId); item.write(uploadedFile); // FileUploadStatus satusBean = FileMgmtFactory.getStatusBean(request); FileInfo fileInfo = new FileInfo(); fileInfo.setCreateDate(new Date()); fileInfo.setFileId(fileId); fileInfo.setFile(uploadedFile); fileInfo.setFilename(FileUtils.getFilename(item.getName())); fileInfo.setSize(item.getSize()); fileInfo.setPath(path); satusBean.getUploadFileUrlList().add(fileInfo); FileMgmtFactory.saveStatusBean(request, satusBean); Thread.sleep(500); } } } catch (FileUploadException ex) { uploadExceptionHandle(request, "?:" + ex.getMessage()); } catch (Exception ex) { uploadExceptionHandle(request, "??:" + ex.getMessage()); } String forwardURL = request.getParameter("forwardURL"); if (StringUtils.isEmpty(forwardURL)) { forwardURL = "/others/attachment.do?method=showResult"; } request.getRequestDispatcher(forwardURL).forward(request, response); }
From source file:cust_photo_upload.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w . j a va2 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 { response.setContentType("text/html;charset=UTF-8"); HttpSession hs = request.getSession(); try (PrintWriter out = response.getWriter()) { Login ln = (Login) hs.getAttribute("user"); String pname = ln.getUName(); String p = ""; // // creates FileItem instances which keep their content in a temporary file on disk FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); //get the list of all fields from request List<FileItem> fields = upload.parseRequest(request); // iterates the object of list Iterator<FileItem> it = fields.iterator(); //getting objects one by one while (it.hasNext()) { //assigning coming object if list to object of FileItem FileItem fileItem = it.next(); //check whether field is form field or not boolean isFormField = fileItem.isFormField(); if (isFormField) { //get the filed name String fieldName = fileItem.getFieldName(); } else { String extension; String fieldName = fileItem.getFieldName(); if (fieldName.equals("photo")) ; { //getting name of file p = new File(fileItem.getName()).getName(); //get the extension of file by diving name into substring extension = p.substring(p.indexOf(".") + 1, p.length()); ; //rename file...concate name and extension p = pname + "." + extension; try { String filePath = this.getServletContext().getRealPath("/images") + "\\"; fileItem.write(new File(filePath + p)); } catch (Exception ex) { out.println(ex.toString()); } } } } // hs.setAttribute("photo", photo); // SessionFactory sf=NewHibernateUtil.getSessionFactory(); // Session s=sf.openSession(); // Transaction t=s.beginTransaction(); // Imagedata im=new Imagedata(); // im.setIname(pname); // im.setIurl(photo); // s.save(im); // t.commit(); // RequestDispatcher rd = request.getRequestDispatcher("viewserv"); rd.forward(request, response); // response.sendRedirect("viewserv"); } catch (Exception ex) { out.println(ex.getMessage()); } }
From source file:fr.inrialpes.exmo.align.service.HTTPTransport.java
/** * Starts a HTTP server to given port.// w w w.j a v a 2 s. co m * * @param params: the parameters of the connection, including HTTP port and host * @param manager: the manager which will deal with connections * @param serv: the set of services to be listening on this connection * @throws AServException when something goes wrong (e.g., socket already in use) */ public void init(Properties params, AServProtocolManager manager, Vector<AlignmentServiceProfile> serv) throws AServException { this.manager = manager; services = serv; tcpPort = Integer.parseInt(params.getProperty("http")); tcpHost = params.getProperty("host"); // ******************************************************************** // JE: Jetty implementation server = new Server(tcpPort); // The handler deals with the request // most of its work is to deal with large content sent in specific ways Handler handler = new AbstractHandler() { public void handle(String String, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String method = request.getMethod(); String uri = request.getPathInfo(); Properties params = new Properties(); try { decodeParams(request.getQueryString(), params); } catch (Exception ex) { logger.debug("IGNORED EXCEPTION: {}", ex); } ; // I do not decode them here because it is useless // See below how it is done. Properties header = new Properties(); Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); header.setProperty(headerName, request.getHeader(headerName)); } // Get the content if any // This is supposed to be only an uploaded file // Note that this could be made more uniform // with the text/xml part stored in a file as well. String mimetype = request.getContentType(); // Multi part: the content provided by an upload HTML form if (mimetype != null && mimetype.startsWith("multipart/form-data")) { try { //if ( !ServletFileUpload.isMultipartContent( request ) ) { // logger.debug( "Does not detect multipart" ); //} DiskFileItemFactory factory = new DiskFileItemFactory(); File tempDir = new File(System.getProperty("java.io.tmpdir")); factory.setRepository(tempDir); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); for (FileItem fi : items) { if (fi.isFormField()) { logger.trace(" >> {} = {}", fi.getFieldName(), fi.getString()); params.setProperty(fi.getFieldName(), fi.getString()); } else { logger.trace(" >> {} : {}", fi.getName(), fi.getSize()); logger.trace(" Stored at {}", fi.getName(), fi.getSize()); try { // FilenameUtils.getName() needed for Internet Explorer problem File uploadedFile = new File(tempDir, FilenameUtils.getName(fi.getName())); fi.write(uploadedFile); params.setProperty("filename", uploadedFile.toString()); params.setProperty("todiscard", "true"); } catch (Exception ex) { logger.warn("Cannot load file", ex); } // Another solution is to run this in /* InputStream uploadedStream = item.getInputStream(); ... uploadedStream.close(); */ } } ; } catch (FileUploadException fuex) { logger.trace("Upload Error", fuex); } } else if (mimetype != null && mimetype.startsWith("text/xml")) { // Most likely Web service request (REST through POST) int length = request.getContentLength(); if (length > 0) { char[] mess = new char[length + 1]; try { new BufferedReader(new InputStreamReader(request.getInputStream())).read(mess, 0, length); } catch (Exception e) { logger.debug("IGNORED Exception", e); } params.setProperty("content", new String(mess)); } // File attached to SOAP messages } else if (mimetype != null && mimetype.startsWith("application/octet-stream")) { File alignFile = new File(File.separator + "tmp" + File.separator + newId() + "XXX.rdf"); // check if file already exists - and overwrite if necessary. if (alignFile.exists()) alignFile.delete(); FileOutputStream fos = new FileOutputStream(alignFile); InputStream is = request.getInputStream(); try { byte[] buffer = new byte[4096]; int bytes = 0; while (true) { bytes = is.read(buffer); if (bytes < 0) break; fos.write(buffer, 0, bytes); } } catch (Exception e) { } finally { fos.flush(); fos.close(); } is.close(); params.setProperty("content", ""); params.setProperty("filename", alignFile.getAbsolutePath()); } // Get the answer (HTTP) HTTPResponse r = serve(uri, method, header, params); // Return it response.setContentType(r.getContentType()); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println(r.getData()); ((Request) request).setHandled(true); } }; server.setHandler(handler); // Common part try { server.start(); } catch (Exception e) { throw new AServException("Cannot launch HTTP Server", e); } //server.join(); // ******************************************************************** //if ( params.getProperty( "wsdl" ) != null ){ // wsmanager = new WSAServProfile(); // if ( wsmanager != null ) wsmanager.init( params, manager ); //} //if ( params.getProperty( "http" ) != null ){ // htmanager = new HTMLAServProfile(); // if ( htmanager != null ) htmanager.init( params, manager ); //} myId = "LocalHTMLInterface"; serverId = manager.serverURL(); logger.info("Launched on {}/html/", serverId); localId = 0; }