List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory setRepository
public void setRepository(File repository)
From source file:classes.Upload.java
public static String uploadImage(HttpServletRequest request, ServletConfig config, String path) throws FileUploadException, Exception { String url = ""; String imgDir = config.getServletContext().getRealPath(path) + "/"; File dir = new File(imgDir); dir.mkdirs();//from w w w . java 2 s . co m System.out.println("PasaPorAqui2"); DiskFileItemFactory fabrica = new DiskFileItemFactory(); fabrica.setSizeThreshold(1024); fabrica.setRepository(dir); ServletFileUpload upload = new ServletFileUpload(fabrica); List<FileItem> partes = upload.parseRequest(request); for (FileItem item : partes) { System.out.println("Subiendo"); File archivo = new File(imgDir, item.getName()); item.write(archivo); url = item.getName(); } return url; }
From source file:com.mobiaware.util.UploadHelpers.java
public static File createUploadFile(final HttpServletRequest request) { DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); fileItemFactory.setSizeThreshold(THRESHOLD_SIZE); fileItemFactory.setRepository(FileUtils.getTempDirectory()); ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory); servletFileUpload.setFileSizeMax(MAX_FILE_SIZE); servletFileUpload.setSizeMax(REQUEST_SIZE); File file = null;//from ww w .j a v a 2 s . c o m try { FileItemIterator fileItemIterator = servletFileUpload.getItemIterator(request); while (fileItemIterator.hasNext()) { FileItemStream fileItem = fileItemIterator.next(); if (fileItem.isFormField()) { // ignore } else { file = File.createTempFile("liim_", null); InputStream is = new BufferedInputStream(fileItem.openStream()); FileUtils.copyInputStreamToFile(is, file); } } } catch (IOException e) { LOG.error(Throwables.getStackTraceAsString(e)); } catch (FileUploadException e) { LOG.error(Throwables.getStackTraceAsString(e)); } return file; }
From source file:com.openmeap.util.ServletUtils.java
/** * @param modelManager/* ww w .ja v a 2 s . c o m*/ * @param request * @param map * @return * @throws FileUploadException */ static final public Boolean handleFileUploads(Integer maxFileUploadSize, String fileStoragePrefix, HttpServletRequest request, Map<Object, Object> map) throws FileUploadException { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(4096); factory.setRepository(new File(fileStoragePrefix)); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxFileUploadSize); List fileItems = upload.parseRequest(request); for (FileItem item : (List<FileItem>) fileItems) { // we'll put this in the parameter map, // assuming the backing that is looking for it // knows what to expect String fieldName = item.getFieldName(); Boolean isFormField = item.isFormField(); Long size = item.getSize(); if (isFormField) { if (size > 0) { map.put(fieldName, new String[] { item.getString() }); } } else if (!isFormField) { map.put(fieldName, item); } } return true; }
From source file:com.intbit.FileUploadUtil.java
public static String uploadFile(String uploadPath, HttpServletRequest request) throws FileUploadException, Exception { logger.info("FileUploadUtil::Entering FileUploadUtil#uploadFile"); String fileName = null;//from ww w . j a va 2s .c o m logger.info("FileUploadUtil::Upload path without filename: " + uploadPath); 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(AppConstants.TMP_FOLDER)); // 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(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!(fi.isFormField())) { // Get the uploaded file parameters fileName = fi.getName(); if (!"".equals(fileName)) { File uploadDir = new File(uploadPath); boolean result = false; if (!uploadDir.exists()) { result = uploadDir.mkdirs(); } // Write the file String filePath = uploadPath + File.separator + fileName; logger.info("FileUploadUtil::Upload path with filename" + filePath); File storeFile = new File(filePath); fi.write(storeFile); logger.info("FileUploadUtil::File Uploaded successfully"); } else { throw new IllegalArgumentException("Filename of uploded file cannot be empty"); } } } return fileName; }
From source file:edu.cornell.mannlib.vitro.webapp.controller.MultipartRequestWrapper.java
/** * Create an upload handler that will throw an exception if the file is too * large./*from w ww. j a va 2 s. c om*/ */ private static ServletFileUpload createUploadHandler(HttpServletRequest req, long maxFileSize) { File tempDir = figureTemporaryDirectory(req); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD); factory.setRepository(tempDir); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxFileSize); return upload; }
From source file:com.google.caja.ancillary.servlet.UploadPage.java
static void doUpload(HttpServletRequest req, HttpServletResponse resp) throws IOException { // Process the uploaded items List<ObjectConstructor> uploads = Lists.newArrayList(); if (ServletFileUpload.isMultipartContent(req)) { // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); int maxUploadSizeBytes = 1 << 18; factory.setSizeThreshold(maxUploadSizeBytes); // In-memory threshold factory.setRepository(new File("/dev/null")); // Do not store on disk ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxUploadSizeBytes); writeHeader(resp);// w ww . j av a 2 s .c o m // Parse the request List<?> items; try { items = upload.parseRequest(req); } catch (FileUploadException ex) { ex.printStackTrace(); resp.getWriter().write(Nodes.encode(ex.getMessage())); return; } for (Object fileItemObj : items) { FileItem item = (FileItem) fileItemObj; // Written for pre-generic java. if (!item.isFormField()) { // Then is a file FilePosition unk = FilePosition.UNKNOWN; String ct = item.getContentType(); uploads.add((ObjectConstructor) QuasiBuilder.substV("({ i: @i, ip: @ip, it: @it? })", "i", StringLiteral.valueOf(unk, item.getString()), "ip", StringLiteral.valueOf(unk, item.getName()), "it", ct != null ? StringLiteral.valueOf(unk, ct) : null)); } } } else if (req.getParameter("url") != null) { List<URI> toFetch = Lists.newArrayList(); boolean failed = false; for (String value : req.getParameterValues("url")) { try { toFetch.add(new URI(value)); } catch (URISyntaxException ex) { if (!failed) { failed = true; resp.setStatus(500); resp.setContentType("text/html;charset=UTF-8"); } resp.getWriter().write("<p>Bad URI: " + Nodes.encode(ex.getMessage())); } } if (failed) { return; } writeHeader(resp); FilePosition unk = FilePosition.UNKNOWN; for (URI uri : toFetch) { try { Content c = UriFetcher.fetch(uri); if (c.isText()) { uploads.add((ObjectConstructor) QuasiBuilder.substV("({ i: @i, ip: @ip, it: @it? })", "i", StringLiteral.valueOf(unk, c.getText()), "ip", StringLiteral.valueOf(unk, uri.toString()), "it", StringLiteral.valueOf(unk, c.type.mimeType))); } } catch (IOException ex) { resp.getWriter() .write("<p>" + Nodes.encode("Failed to fetch URI: " + uri + " : " + ex.getMessage())); } } } else { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); resp.getWriter().write("Content not multipart"); return; } Expression notifyParent = (Expression) QuasiBuilder.substV( "window.parent.uploaded([@uploads*], window.name)", "uploads", new ParseTreeNodeContainer(uploads)); StringBuilder jsBuf = new StringBuilder(); RenderContext rc = new RenderContext(new JsMinimalPrinter(new Concatenator(jsBuf))).withEmbeddable(true); notifyParent.render(rc); rc.getOut().noMoreTokens(); HtmlQuasiBuilder b = HtmlQuasiBuilder.getBuilder(DomParser.makeDocument(null, null)); Writer out = resp.getWriter(); out.write(Nodes.render(b.substV("<script>@js</script>", "js", jsBuf.toString()))); }
From source file:beans.service.FileUploadTool.java
static public String FileUpload(Map<String, String> fields, List<String> filesOnServer, HttpServletRequest request, HttpServletResponse response) { boolean isMultipart = ServletFileUpload.isMultipartContent(request); DiskFileItemFactory factory = new DiskFileItemFactory(); int MaxMemorySize = 10000000; int MaxRequestSize = MaxMemorySize; String tmpDir = System.getProperty("TMP", "/tmp"); System.out.printf("temporary directory:%s", tmpDir); factory.setSizeThreshold(MaxMemorySize); factory.setRepository(new File(tmpDir)); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(MaxRequestSize);/*from w w w. ja v a2 s . com*/ // Parse the request try { List<FileItem> items = upload.parseRequest(request); // Process the uploaded items Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) {//k -v String name = item.getFieldName(); String value = item.getString(); fields.put(name, value); } else { String fieldName = item.getFieldName(); String fileName = item.getName(); if (fileName == null || fileName.length() < 1) { return "file name is empty."; } String localFileName = ServletConfig.fileServerRootDir + File.separator + "tmp" + File.separator + fileName; System.out.printf("upload file:%s", localFileName); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); File uploadedFile = new File(localFileName); item.write(uploadedFile); filesOnServer.add(localFileName); } } return "success"; } catch (FileUploadException e) { e.printStackTrace(); return e.toString(); } catch (Exception e) { e.printStackTrace(); return e.toString(); } }
From source file:com.news.util.UploadFileUtil.java
public static String upload(HttpServletRequest request, String paramName, String fileName) { String result = ""; File file;/*from w w w .j a v a 2s .c om*/ int maxFileSize = 5000 * 1024; int maxMemSize = 5000 * 1024; String filePath = ""; ///opt/apache-tomcat-7.0.59/webapps/noithat //filePath = getServletContext().getRealPath("") + File.separator + "test-upload" + File.separator; filePath = File.separator + File.separator + "opt" + File.separator + File.separator; filePath += "apache-tomcat-7.0.59" + File.separator + File.separator + "webapps"; filePath += File.separator + File.separator + "noithat"; filePath += File.separator + File.separator + "upload" + File.separator + File.separator; filePath += "images" + File.separator; //filePath = "E:" + File.separator; // Verify the content type String contentType = request.getContentType(); System.out.println("contentType=" + contentType); if (contentType != null && (contentType.indexOf("multipart/form-data") >= 0)) { 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); try { // Parse the request to get file items. List fileItems = upload.parseRequest(request); System.out.println("fileItems.size()=" + fileItems.size()); // Process the uploaded file items Iterator i = fileItems.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField() && fi.getFieldName().equals(paramName)) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); int dotPos = fi.getName().lastIndexOf("."); if (dotPos < 0) { fileName += ".jpg"; } else { fileName += fi.getName().substring(dotPos); } 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); System.out.println("Uploaded Filename: " + filePath + fileName + "<br>"); result = fileName; } } } catch (Exception ex) { ex.printStackTrace(); } } return result; }
From source file:edu.isi.webserver.FileUtil.java
static public File downloadFileFromHTTPRequest(HttpServletRequest request) { // Download the file to the upload file folder File destinationDir = new File(DESTINATION_DIR_PATH); logger.info("File upload destination directory: " + destinationDir.getAbsolutePath()); if (!destinationDir.isDirectory()) { destinationDir.mkdir();/*from ww w.ja v a2 s . c om*/ } DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); // Set the size threshold, above which content will be stored on disk. fileItemFactory.setSizeThreshold(1 * 1024 * 1024); //1 MB //Set the temporary directory to store the uploaded files of size above threshold. fileItemFactory.setRepository(destinationDir); ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); File uploadedFile = null; try { // Parse the request @SuppressWarnings("rawtypes") List items = uploadHandler.parseRequest(request); @SuppressWarnings("rawtypes") Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); // Ignore Form Fields. if (item.isFormField()) { System.out.println(item.getFieldName()); System.out.println(item.getString()); // Do nothing } else { //Handle Uploaded files. Write file to the ultimate location. System.out.println("File field name: " + item.getFieldName()); uploadedFile = new File(destinationDir, item.getName()); item.write(uploadedFile); System.out.println("File written to: " + uploadedFile.getAbsolutePath()); } } } catch (FileUploadException ex) { logger.error("Error encountered while parsing the request", ex); } catch (Exception ex) { logger.error("Error encountered while uploading file", ex); } return uploadedFile; }
From source file:edu.isi.karma.util.FileUtil.java
static public File downloadFileFromHTTPRequest(HttpServletRequest request, String destinationDirString) { // Download the file to the upload file folder File destinationDir = new File(destinationDirString); logger.debug("File upload destination directory: " + destinationDir.getAbsolutePath()); DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); // Set the size threshold, above which content will be stored on disk. fileItemFactory.setSizeThreshold(1 * 1024 * 1024); //1 MB //Set the temporary directory to store the uploaded files of size above threshold. fileItemFactory.setRepository(destinationDir); ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); File uploadedFile = null;// w ww .j a v a 2s. c om try { // Parse the request @SuppressWarnings("rawtypes") List items = uploadHandler.parseRequest(request); @SuppressWarnings("rawtypes") Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); // Ignore Form Fields. if (item.isFormField()) { // Do nothing } else { //Handle Uploaded files. Write file to the ultimate location. uploadedFile = new File(destinationDir, item.getName()); if (item instanceof DiskFileItem) { DiskFileItem t = (DiskFileItem) item; if (!t.getStoreLocation().renameTo(uploadedFile)) item.write(uploadedFile); } else item.write(uploadedFile); } } } catch (FileUploadException ex) { logger.error("Error encountered while parsing the request", ex); } catch (Exception ex) { logger.error("Error encountered while uploading file", ex); } return uploadedFile; }