List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload parseRequest
public List parseRequest(HttpServletRequest request) throws FileUploadException
From source file:cn.trymore.core.web.servlet.FileUploadServlet.java
@Override @SuppressWarnings("unchecked") protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); try {/*from w w w .j a v a 2s . c o m*/ DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setSizeThreshold(4096); diskFileItemFactory.setRepository(new File(this.tempPath)); String fileIds = ""; ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); List<FileItem> fileList = (List<FileItem>) servletFileUpload.parseRequest(request); Iterator<FileItem> itor = fileList.iterator(); Iterator<FileItem> itor1 = fileList.iterator(); String file_type = ""; while (itor1.hasNext()) { FileItem item = itor1.next(); if (item.isFormField() && "file_type".equals(item.getFieldName())) { file_type = item.getString(); } } FileItem fileItem; while (itor.hasNext()) { fileItem = itor.next(); if (fileItem.getContentType() == null) { continue; } // obtains the file path and name String filePath = fileItem.getName(); String fileName = filePath.substring(filePath.lastIndexOf("/") + 1); // generates new file name with the current time stamp. String newFileName = this.fileCat + "/" + UtilFile.generateFilename(fileName); // ensure the directory existed before creating the file. File dir = new File( this.uploadPath + "/" + newFileName.substring(0, newFileName.lastIndexOf("/") + 1)); if (!dir.exists()) { dir.mkdirs(); } // stream writes to the destination file fileItem.write(new File(this.uploadPath + "/" + newFileName)); ModelFileAttach fileAttach = null; if (request.getParameter("noattach") == null) { // storages the file into database. fileAttach = new ModelFileAttach(); fileAttach.setFileName(fileName); fileAttach.setFilePath(newFileName); fileAttach.setTotalBytes(Long.valueOf(fileItem.getSize())); fileAttach.setNote(this.getStrFileSize(fileItem.getSize())); fileAttach.setFileExt(fileName.substring(fileName.lastIndexOf(".") + 1)); fileAttach.setCreatetime(new Date()); fileAttach.setDelFlag(ModelFileAttach.FLAG_NOT_DEL); fileAttach.setFileType(!"".equals(file_type) ? file_type : this.fileCat); ModelAppUser user = ContextUtil.getCurrentUser(); if (user != null) { fileAttach.setCreatorId(Long.valueOf(user.getId())); fileAttach.setCreator(user.getFullName()); } else { fileAttach.setCreator("Unknow"); } this.serviceFileAttach.save(fileAttach); } //add by Tang ??fileIds????? if (fileAttach != null) { fileIds = (String) request.getSession().getAttribute("fileIds"); if (fileIds == null) { fileIds = fileAttach.getId(); } else { fileIds = fileIds + "," + fileAttach.getId(); } } response.setContentType("text/html;charset=UTF-8"); PrintWriter writer = response.getWriter(); writer.println( "{\"status\": 1, \"data\":{\"id\":" + (fileAttach != null ? fileAttach.getId() : "\"\"") + ", \"url\":\"" + newFileName + "\"}}"); } request.getSession().setAttribute("fileIds", fileIds); } catch (Exception e) { e.printStackTrace(); response.getWriter().write("{\"status\":0, \"message\":\":" + e.getMessage() + "\""); } }
From source file:com.ephesoft.dcma.gwt.foldermanager.server.UploadDownloadFilesServlet.java
private void uploadFile(HttpServletRequest req, String currentBatchUploadFolderName) throws IOException { File tempFile = null;/* w ww . java 2 s. co m*/ InputStream instream = null; OutputStream out = null; String uploadFileName = EMPTY_STRING; if (ServletFileUpload.isMultipartContent(req)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); uploadFileName = EMPTY_STRING; String uploadFilePath = EMPTY_STRING; List<FileItem> items; try { items = upload.parseRequest(req); for (FileItem item : items) { if (!item.isFormField()) { uploadFileName = item.getName(); if (uploadFileName != null) { uploadFileName = uploadFileName .substring(uploadFileName.lastIndexOf(File.separator) + 1); } uploadFilePath = currentBatchUploadFolderName + File.separator + uploadFileName; try { instream = item.getInputStream(); tempFile = new File(uploadFilePath); out = new FileOutputStream(tempFile); byte buf[] = new byte[1024]; int len = instream.read(buf); while (len > 0) { out.write(buf, 0, len); len = instream.read(buf); } } catch (FileNotFoundException e) { LOG.error(UNABLE_TO_CREATE_THE_UPLOAD_FOLDER_PLEASE_TRY_AGAIN); } catch (IOException e) { LOG.error(UNABLE_TO_READ_THE_FILE_PLEASE_TRY_AGAIN); } finally { if (out != null) { out.close(); } if (instream != null) { instream.close(); } } } } } catch (FileUploadException e) { LOG.error(UNABLE_TO_READ_THE_FORM_CONTENTS_PLEASE_TRY_AGAIN); } LOG.info(THE_CURRENT_UPLOAD_FOLDER_NAME_IS + currentBatchUploadFolderName); LOG.info(THE_NAME_OF_FILE_BEING_UPLOADED_IS + uploadFileName); } else { LOG.error(REQUEST_CONTENTS_TYPE_IS_NOT_SUPPORTED); } }
From source file:adminShop.registraProducto.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* ww w . ja v a2s . 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 { String message = "Error"; boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items; HashMap hm = new HashMap(); ArrayList<Imagen> imgs = new ArrayList<>(); Producto prod = new Producto(); Imagen img = null; try { items = upload.parseRequest(request); Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) { String name = item.getFieldName(); String value = item.getString(); hm.put(name, value); } else { img = new Imagen(); String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeBytes = item.getSize(); File file = new File("/home/gama/Escritorio/adoo/" + fileName + ".jpg"); item.write(file); Path path = Paths.get("/home/gama/Escritorio/adoo/" + fileName + ".jpg"); byte[] data = Files.readAllBytes(path); byte[] encode = org.apache.commons.codec.binary.Base64.encodeBase64(data); img.setUrl(new javax.sql.rowset.serial.SerialBlob(encode)); imgs.add(img); //file.delete(); } } prod.setNombre((String) hm.get("nombre")); prod.setProdNum((String) hm.get("prodNum")); prod.setDesc((String) hm.get("desc")); prod.setIva(Double.parseDouble((String) hm.get("iva"))); prod.setPrecio(Double.parseDouble((String) hm.get("precio"))); prod.setPiezas(Integer.parseInt((String) hm.get("piezas"))); prod.setEstatus("A"); prod.setImagenes(imgs); ProductoDAO prodDAO = new ProductoDAO(); if (prodDAO.registraProducto(prod)) { message = "Exito"; } } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } response.sendRedirect("index.jsp"); }
From source file:com.food.adminservlet.FoodServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int foodid = 0; String foodName = ""; String fooddesc = ""; Double foodprice = 0.0;// w ww . jav a 2s . c o m String foodCategory = ""; PrintWriter out = response.getWriter(); isMultipart = ServletFileUpload.isMultipartContent(request); FoodBean bkfood = new FoodBean(); FoodBL foodbl = new FoodBL(); try { 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:\\temp")); // 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>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (fi.isFormField()) { if (fi.getFieldName().equals("foodid")) { foodid = Integer.parseInt(fi.getString()); } if (fi.getFieldName().equals("foodname")) { foodName = fi.getString(); } if (fi.getFieldName().equals("fooddesc")) { fooddesc = fi.getString(); } if (fi.getFieldName().equals("foodprice")) { foodprice = Double.parseDouble(fi.getString()); } if (fi.getFieldName().equals("foodcate")) { foodCategory = fi.getString(); } out.println("<br>"); } 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(); // 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>"); } } out.println(fileName); bkfood.setFoodId(foodid); bkfood.setFoodName(foodName); bkfood.setFoodPrice(foodprice); bkfood.setFoodCateg(foodCategory); bkfood.setFoodDesc(fooddesc); bkfood.setFoodRetreiveImage(fileName); // bkfood.setFoodimage(request.getPart("foodimage")); bkfood.setFoodstatus("Y"); int chk = foodbl.addFoodItems(bkfood); out.println(chk); if (chk == 1) { response.sendRedirect("food.jsp"); } } catch (Exception ex) { out.println(ex); } }
From source file:com.cognitivabrasil.repositorio.web.FileController.java
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST) @ResponseBody/*from w w w . j a v a 2s . co m*/ public String upload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, org.apache.commons.fileupload.FileUploadException { if (file == null) { file = new Files(); file.setSizeInBytes(0L); } Integer docId = null; String docPath = null; String responseString = RESP_SUCCESS; boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { try { ServletFileUpload x = new ServletFileUpload(new DiskFileItemFactory()); List<FileItem> items = x.parseRequest(request); for (FileItem item : items) { InputStream input = item.getInputStream(); // Handle a form field. if (item.isFormField()) { String attribute = item.getFieldName(); String value = Streams.asString(input); switch (attribute) { case "chunks": this.chunks = Integer.parseInt(value); break; case "chunk": this.chunk = Integer.parseInt(value); break; case "filename": file.setName(value); break; case "docId": if (value.isEmpty()) { throw new org.apache.commons.fileupload.FileUploadException( "No foi informado o id do documento."); } docId = Integer.parseInt(value); docPath = Config.FILE_PATH + "/" + docId; File documentPath = new File(docPath); // cria o diretorio documentPath.mkdirs(); break; default: break; } } // Handle a multi-part MIME encoded file. else { try { File uploadFile = new File(docPath, item.getName()); BufferedOutputStream bufferedOutput; bufferedOutput = new BufferedOutputStream(new FileOutputStream(uploadFile, true)); byte[] data = item.get(); bufferedOutput.write(data); bufferedOutput.close(); } catch (Exception e) { LOG.error("Erro ao salvar o arquivo.", e); file = null; throw e; } finally { if (input != null) { try { input.close(); } catch (IOException e) { LOG.error("Erro ao fechar o ImputStream", e); } } file.setName(item.getName()); file.setContentType(item.getContentType()); file.setPartialSize(item.getSize()); } } } if ((this.chunk == this.chunks - 1) || this.chunks == 0) { file.setLocation(docPath + "/" + file.getName()); if (docId != null) { file.setDocument(documentsService.get(docId)); } fileService.save(file); file = null; } } catch (org.apache.commons.fileupload.FileUploadException | IOException | NumberFormatException e) { responseString = RESP_ERROR; LOG.error("Erro ao salvar o arquivo", e); file = null; throw e; } } // Not a multi-part MIME request. else { responseString = RESP_ERROR; } response.setContentType("application/json"); byte[] responseBytes = responseString.getBytes(); response.setContentLength(responseBytes.length); ServletOutputStream output = response.getOutputStream(); output.write(responseBytes); output.flush(); return responseString; }
From source file:com.shyshlav.functions.filework.download_image.java
public String download(HttpServletRequest request, HttpServletResponse response) throws IOException { request.setCharacterEncoding("UTF-8"); // response.setCharacterEncoding("UTF-8"); filePath = request.getSession().getServletContext().getInitParameter("avathars"); System.out.println(filePath); isMultipart = ServletFileUpload.isMultipartContent(request); System.out.println(isMultipart); response.setContentType("text/html"); PrintWriter out = response.getWriter(); if (!isMultipart) { return " "; }//from ww w. ja v a2 s . c o m 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:\test")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); try { // Parse the request to get file items. List<FileItem> fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); //String name,String password,String email,String surname,String link_to_image,String about_me,String id String name = null; String password = null; String re_password = null; String surname = null; String about_me = null; String id = null; String link_to_server = null; String email = null; while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (fi.isFormField()) { String fieldname = fi.getFieldName(); String fieldvalue = fi.getString(); if (fieldname.equals("name")) { name = fi.getString("UTF-8"); } else if (fieldname.equals("surname")) { surname = fi.getString("UTF-8"); } else if (fieldname.equals("password")) { password = fi.getString("UTF-8"); } else if (fieldname.equals("re_password")) { re_password = fi.getString("UTF-8"); } else if (fieldname.equals("about_me")) { about_me = fi.getString("UTF-8"); } else if (fieldname.equals("id")) { id = fi.getString("UTF-8"); } else if (fieldname.equals("email")) { email = fi.getString("UTF-8"); } System.out.println(fieldname + fieldvalue); if (fieldname == null || fieldvalue == null) { return "? ? ? "; } } if (!fi.isFormField()) { if (!password.equals(re_password)) { System.out.println(password + " - " + re_password); return " ?"; } // Get the uploaded file parameters String fileName = email + ".png"; link_to_server = "/musicbox/avathars/" + email + ".png".trim(); // 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); System.out.println("Uploaded Filename: " + filePath + fileName); } } System.out.println(link_to_server); updateUser um = new updateUser(); um.updateUser(name, password, surname, link_to_server, about_me, id); } catch (Exception ex) { System.out.println(ex); return " 1 "; } return "ok"; }
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 . j a va 2 s. c o 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:net.morphbank.mbsvc3.webservices.RestfulService.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); MorphbankConfig.SYSTEM_LOGGER.info("starting post"); response.setContentType("text/xml"); System.err.println("<!-- persistence: " + MorphbankConfig.getPersistenceUnit() + " -->"); MorphbankConfig.SYSTEM_LOGGER.info("<!-- filepath: " + filepath + " -->"); boolean isMultipart = ServletFileUpload.isMultipartContent(request); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); // response.setContentType("text/html"); try {//from w w w.j a v a 2 s .c o m // Process the uploaded items List<?> /* FileItem */ items = upload.parseRequest(request); Iterator<?> iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { MorphbankConfig.SYSTEM_LOGGER.info("Form field " + item.getFieldName()); // processFormField(item); } else { // processUploadedFile(item); String paramName = item.getFieldName(); String fileName = item.getName(); InputStream stream = item.getInputStream(); // Reader reader = new InputStreamReader(stream); if ("uploadFileXml".equals(paramName)) { MorphbankConfig.SYSTEM_LOGGER.info("Processing file " + fileName); processRequest(stream, out, fileName); MorphbankConfig.SYSTEM_LOGGER.info("Processing complete"); } else { // Process the input stream MorphbankConfig.SYSTEM_LOGGER .info("Upload field name " + item.getFieldName() + " ignored!"); } } } } catch (FileUploadException e) { e.printStackTrace(); } }
From source file:UploadDownloadFile.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response);//from w w w.j av a 2s .com String filePath; final String clientip = request.getRemoteAddr().replace(":", "_"); filePath = "/Users/" + currentuser + "/GlassFish_Server/glassfish/domains/domain1/tmpfiles/Uploaded/" + clientip + "/"; System.out.println("filePath = " + filePath); // filePath = "/Users/jhovarie/Desktop/webuploaded/"; File f = new File(filePath); if (!f.exists()) { f.mkdirs(); } isMultipart = ServletFileUpload.isMultipartContent(request); response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); if (!isMultipart) { 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>"); return; } 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:\\temp")); factory.setRepository(new File(filePath)); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); try { // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); out.println("<a href='" + currenthost + "/UploadDownloadFile/index.html'><< BACK <<</a><br/>"); String fileName = ""; 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(); // 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>"); } } out.println("Target Location = " + filePath); out.write( "<br/><a href=\"UploadDownloadFile?fileName=" + fileName + "\">Download " + fileName + "</a>"); out.println("</body>"); out.println("</html>"); } catch (Exception ex) { System.out.println("Error in Process " + ex); } }
From source file:datalab.upo.ladonspark.controller.uploadFile.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// w w 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 */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, Exception { List<objectresult> lor = new ArrayList<>(); List<objectresult> loraux = new ArrayList<>(); boolean result = false; String urlf = ""; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); // req es la HttpServletRequest que recibimos del formulario. // Los items obtenidos sern cada uno de los campos del formulario, // tanto campos normales como ficheros subidos. List items = upload.parseRequest(request); // Se recorren todos los items, que son de tipo FileItem for (Object item : items) { FileItem uploaded = (FileItem) item; // Hay que comprobar si es un campo de formulario. Si no lo es, se guarda el fichero // subido donde nos interese if (!uploaded.isFormField()) { // No es campo de formulario, guardamos el fichero en algn sitio if (!uploaded.getName().equals("")) { urlf = uploaded.getName(); File fichero = new File(this.getPath() + "src/main/webapp/algorithm/dataAlgoritm/", uploaded.getName()); uploaded.write(fichero); } else { result = true; } } else { // es un campo de formulario, podemos obtener clave y valor String key = uploaded.getFieldName(); String value = uploaded.getString(); lor.add(new objectresult(key, value)); if (value == null || value.equals("")) { result = true; } } } if (result) { request.getSession().setAttribute("error", "error"); String url = "algorithm/addalgo.jsp"; response.sendRedirect(url); } else { Algorithm a = new Algorithm(lor.get(0).getValue(), lor.get(1).getValue(), urlf); DaoAlgoritm da = new DaoAlgoritm(); da.create(a); a = da.getAlgoritm(a.getNameAlg()); DaoParameter dp = new DaoParameter(); for (int i = 3; i < lor.size(); i++) { dp.create(new Parameter(a, lor.get(i).getValue(), lor.get(i + 1).getValue())); i++; } request.getSession().setAttribute("algorithm", new DaoAlgoritm().optenerAlgoritmos()); String url = "algorithm/masteralgo.jsp"; response.sendRedirect(url); } }