List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory setRepository
public void setRepository(File repository)
From source file:nl.armatiek.xslweb.serializer.RequestSerializer.java
private List<FileItem> getMultipartContentItems() throws IOException, FileUploadException { List<FileItem> items = null; boolean isMultipart = ServletFileUpload.isMultipartContent(req); if (isMultipart) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(0);/*w w w . j a v a2s .co m*/ reposDir = new File(FileUtils.getTempDirectory(), File.separatorChar + UUID.randomUUID().toString()); if (!reposDir.mkdirs()) { throw new XSLWebException( String.format("Could not create DiskFileItemFactory repository directory (%s)", reposDir.getAbsolutePath())); } factory.setRepository(reposDir); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(1024 * 1024 * webApp.getMaxUploadSize()); items = upload.parseRequest(req); } return items; }
From source file:nl.fontys.pts61a.vps.controller.UploadController.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (!ServletFileUpload.isMultipartContent(request)) { PrintWriter writer = response.getWriter(); writer.println("Error: Form must has enctype=multipart/form-data."); writer.flush();//from w ww . j a v a 2 s . c o m return; } DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(MEMORY_THRESHOLD); factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(MAX_FILE_SIZE); upload.setSizeMax(MAX_REQUEST_SIZE); String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY; File uploadDir = new File("verplaatsingen"); if (!uploadDir.exists()) { uploadDir.mkdir(); } try { @SuppressWarnings("unchecked") List<FileItem> formItems = upload.parseRequest(request); if (formItems != null && formItems.size() > 0) { for (FileItem item : formItems) { if (!item.isFormField()) { final InputStream stream = item.getInputStream(); final byte[] bytes = IOUtils.toByteArray(stream); String movementJson = new String(bytes, "UTF-8"); String fileName = new File(item.getName()).getName(); String filePath = uploadPath + File.separator + fileName; File storeFile = new File(filePath); JSONObject json = (JSONObject) new JSONParser().parse(movementJson); Long cartrackerId = Long.parseLong(json.get("cartrackerId").toString()); String verificatieCode = json.get("verificatieCode").toString(); Cartracker c = service.checkCartrackerId(cartrackerId, verificatieCode); Long nextId = c.getLastId() + 1l; if (Objects.equals(nextId, Long.valueOf(json.get("currentId").toString()))) { List<JSONObject> movementsJson = (List<JSONObject>) json.get("verplaatsingen"); for (JSONObject jo : movementsJson) { Movement m = new Movement(); m.setLongitude(Double.parseDouble(jo.get("longitude").toString())); m.setLatitude(Double.parseDouble(jo.get("latitude").toString())); String string = jo.get("date").toString(); java.util.Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse(string); new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(date); m.setRegistrationDate(date); m.setMovementId(Long.parseLong(jo.get("movementId").toString())); m.setDistance(Long.parseLong(jo.get("distance").toString())); m.setCartracker(c); service.addMovement(m); } service.setCartracketNextId(c, nextId); } else { PrintWriter writer = response.getWriter(); writer.println("Missing: " + nextId); writer.flush(); return; } // try { // item.write(storeFile); // } catch (Exception ex) { // Logger.getLogger(UploadController.class.getName()).log(Level.SEVERE, null, ex); // } } } PrintWriter writer = response.getWriter(); writer.println("File uploaded."); writer.flush(); } } catch (ParseException | FileUploadException | java.text.ParseException ex) { Logger.getLogger(UploadController.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:or.tango.server.controller.FileController.java
public void upload(HttpServletRequest request, HttpServletResponse response) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(4 * 1024);// w w w . j a v a 2s . com String tmpdir = request.getSession().getServletContext().getRealPath("/temp/"); File tempd = new File(tmpdir); if (!tempd.exists()) { tempd.mkdirs(); } factory.setRepository(tempd); ServletFileUpload upload = new ServletFileUpload(factory); Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddkkmmssSSS"); String filedir = sdf.format(date); String result = null; try { FileItem item = upload.parseRequest(request).get(0); /** * @author ladd_cn(ladd.cn@gmail.com) * @version 1.0 * @date 2013/8/23 * @modify 1:start */ String fileDirectory = request.getSession().getServletContext().getRealPath("/images/" + filedir); if (!isPicture(item.getName(), null)) { System.out.println("Illegel file type"); result = null; } else { File dir = new File(fileDirectory); if (!dir.exists()) { dir.mkdirs(); } File file = new File(fileDirectory + "/" + item.getName()); /** * @modify 1:end */ item.write(file); result = FileService.pickupText(file); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } BaseController.resonseJson(response, result); }
From source file:org.ala.layers.web.ShapesService.java
@RequestMapping(value = "/shape/upload/shp", method = RequestMethod.POST) @ResponseBody/*from w w w .ja va 2 s . co m*/ public Map<Object, Object> uploadShapeFile(HttpServletRequest req, HttpServletResponse resp, @RequestParam(value = "user_id", required = false) String userId, @RequestParam(value = "api_key", required = false) String apiKey) throws Exception { // Use linked hash map to maintain key ordering Map<Object, Object> retMap = new LinkedHashMap<Object, Object>(); File tmpZipFile = File.createTempFile("shpUpload", ".zip"); if (!ServletFileUpload.isMultipartContent(req)) { String jsonRequestBody = IOUtils.toString(req.getReader()); JSONRequestBodyParser reqBodyParser = new JSONRequestBodyParser(); reqBodyParser.addParameter("user_id", String.class, false); reqBodyParser.addParameter("shp_file_url", String.class, false); reqBodyParser.addParameter("api_key", String.class, false); if (reqBodyParser.parseJSON(jsonRequestBody)) { String shpFileUrl = (String) reqBodyParser.getParsedValue("shp_file_url"); userId = (String) reqBodyParser.getParsedValue("user_id"); apiKey = (String) reqBodyParser.getParsedValue("api_key"); if (!checkAPIKey(apiKey, userId)) { retMap.put("error", "Invalid user ID or API key"); return retMap; } // Use shape file url from json body IOUtils.copy(new URL(shpFileUrl).openStream(), new FileOutputStream(tmpZipFile)); retMap.putAll(handleZippedShapeFile(tmpZipFile)); } else { retMap.put("error", StringUtils.join(reqBodyParser.getErrorMessages(), ",")); } } else { if (!checkAPIKey(apiKey, userId)) { retMap.put("error", "Invalid user ID or API key"); return retMap; } // Create a factory for disk-based file items. File size limit is // 50MB // Configure a repository (to ensure a secure temp location is used) File repository = new File(System.getProperty("java.io.tmpdir")); DiskFileItemFactory factory = new DiskFileItemFactory(1024 * 1024 * 50, repository); factory.setRepository(repository); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List<FileItem> items = upload.parseRequest(req); if (items.size() == 1) { FileItem fileItem = items.get(0); IOUtils.copy(fileItem.getInputStream(), new FileOutputStream(tmpZipFile)); retMap.putAll(handleZippedShapeFile(tmpZipFile)); } else { retMap.put("error", "Multiple files sent in request. A single zipped shape file should be supplied."); } } return retMap; }
From source file:org.apache.flink.client.web.JobsServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // check, if we are doing the right request if (!ServletFileUpload.isMultipartContent(req)) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return;//from www . ja v a 2s . c o m } // create the disk file factory, limiting the file size to 20 MB DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); fileItemFactory.setSizeThreshold(20 * 1024 * 1024); // 20 MB fileItemFactory.setRepository(tmpDir); String filename = null; // parse the request ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); try { Iterator<FileItem> itr = ((List<FileItem>) uploadHandler.parseRequest(req)).iterator(); // go over the form fields and look for our file while (itr.hasNext()) { FileItem item = itr.next(); if (!item.isFormField()) { if (item.getFieldName().equals("upload_jar_file")) { // found the file, store it to the specified location filename = item.getName(); File file = new File(destinationDir, filename); item.write(file); break; } } } } catch (FileUploadException ex) { resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Invalid Fileupload."); return; } catch (Exception ex) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An unknown error occurred during the file upload."); return; } // write the okay message resp.sendRedirect(targetPage); }
From source file:org.apache.openejb.server.httpd.part.CommonsFileUploadPartFactory.java
public static Collection<Part> read(final HttpRequestImpl request) { // mainly for testing // Create a new file upload handler final DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(REPO); final ServletFileUpload upload = new ServletFileUpload(); upload.setFileItemFactory(factory);/*w w w. j ava2 s . co m*/ final List<Part> parts = new ArrayList<>(); try { final List<FileItem> items = upload.parseRequest(new ServletRequestContext(request)); final String enc = request.getCharacterEncoding(); for (final FileItem item : items) { final CommonsFileUploadPart part = new CommonsFileUploadPart(item, null); parts.add(part); if (part.getSubmittedFileName() == null) { String name = part.getName(); String value = null; try { String encoding = request.getCharacterEncoding(); if (encoding == null) { if (enc == null) { encoding = "UTF-8"; } else { encoding = enc; } } value = part.getString(encoding); } catch (final UnsupportedEncodingException uee) { try { value = part.getString("UTF-8"); } catch (final UnsupportedEncodingException e) { // not possible } } request.addInternalParameter(name, value); } } return parts; } catch (final FileUploadException e) { throw new IllegalStateException(e); } }
From source file:org.chiba.web.servlet._HttpRequestHandler.java
/** * Parses a HTTP request. Returns an array containing maps for upload * controls, other controls, repeat indices, and trigger. The individual * maps may be null in case no corresponding parameters appear in the * request.//from w w w . j ava 2 s. c o m * * @param request a HTTP request. * @return an array of maps containing the parsed request parameters. * @throws FileUploadException if an error occurred during file upload. * @throws UnsupportedEncodingException if an error occurred during * parameter value decoding. */ protected Map[] parseRequest(HttpServletRequest request) throws FileUploadException, UnsupportedEncodingException { Map[] parameters = new Map[4]; if (FileUploadBase.isMultipartContent(new ServletRequestContext(request))) { UploadListener uploadListener = new UploadListener(request, this.sessionKey); DiskFileItemFactory factory = new MonitoredDiskFileItemFactory(uploadListener); factory.setRepository(new File(this.uploadRoot)); ServletFileUpload upload = new ServletFileUpload(factory); String encoding = request.getCharacterEncoding(); if (encoding == null) { encoding = "UTF-8"; } Iterator iterator = upload.parseRequest(request).iterator(); FileItem item; while (iterator.hasNext()) { item = (FileItem) iterator.next(); if (item.isFormField()) { LOGGER.info("request param: " + item.getFieldName() + " - value='" + item.getString() + "'"); } else { LOGGER.info("file in request: " + item.getName()); } parseMultiPartParameter(item, encoding, parameters); } } else { Enumeration enumeration = request.getParameterNames(); String name; String[] values; while (enumeration.hasMoreElements()) { name = (String) enumeration.nextElement(); values = request.getParameterValues(name); parseURLEncodedParameter(name, values, parameters); } } return parameters; }
From source file:org.cloud.mblog.utils.FileUtil.java
/** * Ckeditor?//w ww . j av a 2 s .c om * * @param request * @return */ public static String processUploadPostForCkeditor(HttpServletRequest request) { LocalDateTime now = LocalDateTime.now(); String realFolder = LOCALROOT + getImageRelativePathByDate(now); String urlPath = getImageUrlPathByDate(now); DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setRepository(new File(realFolder)); ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); servletFileUpload.setFileSizeMax(MAX_FILE_SIZE); MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; Iterator<String> fileNameIter = multipartRequest.getFileNames(); try { while (fileNameIter.hasNext()) { MultipartFile mr = multipartRequest.getFile(fileNameIter.next()); String sourceFileName = mr.getOriginalFilename(); if (StringUtils.isNotBlank(sourceFileName)) { String fileType = sourceFileName.substring(sourceFileName.lastIndexOf(".") + 1); if (ALLOWEXT.contains(fileType)) { String filename = getDateTypeFileName(now, fileType); File targetFile = new File(realFolder + File.separator + filename); logger.info("Upload file path: " + targetFile.getAbsolutePath()); mr.transferTo(targetFile); return urlPath + "/" + filename; } else { logger.error("?: " + fileType); return ""; } } } } catch (IOException e) { logger.error("error", e); } return ""; }
From source file:org.codeartisans.proxilet.Proxilet.java
/** * Sets up the given {@link PostMethod} to send the same multipart POST data as was sent in the given * {@link HttpServletRequest}.// w w w. j av a2 s . c om * * @param postMethodProxyRequest The {@link PostMethod} that we are configuring to send a multipart POST request * @param httpServletRequest The {@link HttpServletRequest} that contains the mutlipart POST data to be sent via the {@link PostMethod} */ @SuppressWarnings("unchecked") private void handleMultipartPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest) throws ServletException { // Create a factory for disk-based file items DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); // Set factory constraints diskFileItemFactory.setSizeThreshold(maxFileUploadSize); diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY); // Create a new file upload handler ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); // Parse the request try { // Get the multipart items as a list List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest); // Create a list to hold all of the parts List<Part> listParts = new ArrayList<Part>(); // Iterate the multipart items list for (FileItem fileItemCurrent : listFileItems) { // If the current item is a form field, then create a string part if (fileItemCurrent.isFormField()) { StringPart stringPart = new StringPart(fileItemCurrent.getFieldName(), // The field name fileItemCurrent.getString() // The field value ); // Add the part to the list listParts.add(stringPart); } else { // The item is a file upload, so we create a FilePart FilePart filePart = new FilePart(fileItemCurrent.getFieldName(), // The field name new ByteArrayPartSource(fileItemCurrent.getName(), // The uploaded file name fileItemCurrent.get() // The uploaded file contents )); // Add the part to the list listParts.add(filePart); } } MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity( listParts.toArray(new Part[] {}), postMethodProxyRequest.getParams()); postMethodProxyRequest.setRequestEntity(multipartRequestEntity); // The current content-type header (received from the client) IS of // type "multipart/form-data", but the content-type header also // contains the chunk boundary string of the chunks. Currently, this // header is using the boundary of the client request, since we // blindly copied all headers from the client request to the proxy // request. However, we are creating a new request with a new chunk // boundary string, so it is necessary that we re-set the // content-type string to reflect the new chunk boundary string postMethodProxyRequest.setRequestHeader(HEADER_CONTENT_TYPE, multipartRequestEntity.getContentType()); } catch (FileUploadException fileUploadException) { throw new ServletException(fileUploadException); } }
From source file:org.codelabor.system.file.web.controller.xplatform.FileController.java
@RequestMapping("/upload-test") public String upload(Model model, HttpServletRequest request, ServletContext context) throws Exception { logger.debug("upload-teset"); DataSetList outputDataSetList = new DataSetList(); VariableList outputVariableList = new VariableList(); try {/*w w w .ja va 2 s . c o m*/ boolean isMultipart = ServletFileUpload.isMultipartContent(request); Map<String, Object> paramMap = RequestUtils.getParameterMap(request); logger.debug("paramMap: {}", paramMap.toString()); String mapId = (String) paramMap.get("mapId"); RepositoryType acceptedRepositoryType = repositoryType; String requestedRepositoryType = (String) paramMap.get("repositoryType"); if (StringUtils.isNotEmpty(requestedRepositoryType)) { acceptedRepositoryType = RepositoryType.valueOf(requestedRepositoryType); } if (isMultipart) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(sizeThreshold); factory.setRepository(new File(tempRepositoryPath)); factory.setFileCleaningTracker(FileCleanerCleanup.getFileCleaningTracker(context)); ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(fileSizeMax); upload.setSizeMax(requestSizeMax); upload.setHeaderEncoding(characterEncoding); upload.setProgressListener(new FileUploadProgressListener()); List<FileItem> fileItemList = upload.parseRequest(request); Iterator<FileItem> iter = fileItemList.iterator(); while (iter.hasNext()) { FileItem fileItem = iter.next(); logger.debug("fileItem: {}", fileItem.toString()); FileDTO fileDTO = null; if (fileItem.isFormField()) { paramMap.put(fileItem.getFieldName(), fileItem.getString(characterEncoding)); } else { if (fileItem.getName() == null || fileItem.getName().length() == 0) continue; // set DTO fileDTO = new FileDTO(); fileDTO.setMapId(mapId); fileDTO.setRealFilename(FilenameUtils.getName(fileItem.getName())); if (acceptedRepositoryType == RepositoryType.FILE_SYSTEM) { fileDTO.setUniqueFilename(uniqueFilenameGenerationService.getNextStringId()); } fileDTO.setContentType(fileItem.getContentType()); fileDTO.setRepositoryPath(realRepositoryPath); logger.debug("fileDTO: {}", fileDTO.toString()); UploadUtils.processFile(acceptedRepositoryType, fileItem.getInputStream(), fileDTO); } if (fileDTO != null) fileManager.insertFile(fileDTO); } } else { } XplatformUtils.setSuccessMessage( messageSource.getMessage("info.success", new Object[] {}, forcedLocale), outputVariableList); logger.debug("success"); } catch (Exception e) { logger.error("fail"); e.printStackTrace(); logger.error(e.getMessage()); throw new XplatformException(messageSource.getMessage("error.failure", new Object[] {}, forcedLocale), e); } model.addAttribute(OUTPUT_DATA_SET_LIST, outputDataSetList); model.addAttribute(OUTPUT_VARIABLE_LIST, outputVariableList); return VIEW_NAME; }