/** 获取所有文本域 */ public static final List<?> getFileItemList(HttpServletRequest request, File saveDir) throws FileUploadException { if (!saveDir.isDirectory()) { saveDir.mkdir(); } List<?> fileItems = null; RequestContext requestContext = new ServletRequestContext(request); if (FileUpload.isMultipartContent(requestContext)) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(saveDir); factory.setSizeThreshold(fileSizeThreshold); ServletFileUpload upload = new ServletFileUpload(factory); fileItems = upload.parseRequest(request); } return fileItems; }
/** 获取所有文本域 */ public static List<?> getFileItemList(HttpServletRequest request, File saveDir) throws FileUploadException { if (!saveDir.isDirectory()) { saveDir.mkdir(); } List<?> fileItems = null; RequestContext requestContext = new ServletRequestContext(request); if (FileUpload.isMultipartContent(requestContext)) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(saveDir); factory.setSizeThreshold(fileSizeThreshold); ServletFileUpload upload = new ServletFileUpload(factory); fileItems = upload.parseRequest(request); } return fileItems; }
protected DiskFileItemFactory createDiskFileItemFactory(String saveDir) { DiskFileItemFactory fac = new DiskFileItemFactory(); // Make sure that the data is written to file fac.setSizeThreshold(0); if (saveDir != null) { fac.setRepository(new File(saveDir)); } return fac; }
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); 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; }
/** * Gets the FileItemIterator of the input. * * Can be used to process uploads in a streaming fashion. Check out: * http://commons.apache.org/fileupload/streaming.html * * @return the FileItemIterator of the request or null if there was an * error. */ public Optional<List<FormItem>> parseRequestMultiPartItems(String encoding) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(properties.getInt(Constants.PROPERTY_UPLOADS_MAX_SIZE/*Constants.Params.maxUploadSize.name()*/));//Configuration.getMaxUploadSize()); factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); //Configuration.getTmpDir()); //README the file for tmpdir *MIGHT* need to go into Properties ServletFileUpload upload = new ServletFileUpload(factory); if(encoding != null) upload.setHeaderEncoding(encoding); upload.setFileSizeMax(properties.getInt(Constants.PROPERTY_UPLOADS_MAX_SIZE)); try { List<FormItem> items = upload.parseRequest(request) .stream() .map(item -> new ApacheFileItemFormItem(item)) .collect(Collectors.toList()); return Optional.of(items); } catch (FileUploadException e) { //"Error while trying to process mulitpart file upload" //README: perhaps some logging } return Optional.empty(); }
@Override public void process(Exchange exchange) throws Exception { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ExchangeFileUpload upload = new ExchangeFileUpload(factory); java.util.List<FileItem> items = upload.parseExchange(exchange); if(items.size() >= 1){ exchange.getIn().setBody(items.get(0).getInputStream()); for (int i = 1; i < items.size(); i++) { exchange.setProperty(items.get(i).getName(), items.get(i).getInputStream()); } } }
public void importProject(HttpServletRequest req, HttpServletResponse resp) throws Exception { DiskFileItemFactory factory = new DiskFileItemFactory(); ServletContext servletContext = req.getSession().getServletContext(); File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir"); factory.setRepository(repository); ServletFileUpload upload = new ServletFileUpload(factory); InputStream inputStream=null; boolean overwriteProject=true; List<FileItem> items = upload.parseRequest(req); if(items.size()==0){ throw new ServletException("Upload file is invalid."); } for(FileItem item:items){ String name=item.getFieldName(); if(name.equals("overwriteProject")){ String overwriteProjectStr=new String(item.get()); overwriteProject=Boolean.valueOf(overwriteProjectStr); }else if(name.equals("file")){ inputStream=item.getInputStream(); } } repositoryService.importXml(inputStream,overwriteProject); IOUtils.closeQuietly(inputStream); resp.sendRedirect(req.getContextPath()+"/urule/frame"); }
public void importExcelTemplate(HttpServletRequest req, HttpServletResponse resp) throws Exception { DiskFileItemFactory factory=new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(req); Iterator<FileItem> itr = items.iterator(); List<Map<String,Object>> mapData=null; while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); String name=item.getFieldName(); if(!name.equals("file")){ continue; } InputStream stream=item.getInputStream(); mapData=parseExcel(stream); httpSessionKnowledgeCache.put(req, IMPORT_EXCEL_DATA, mapData); stream.close(); break; } httpSessionKnowledgeCache.put(req, IMPORT_EXCEL_DATA, mapData); writeObjectToJson(resp, mapData); }
protected void getServiceResult(HttpServletRequest request, Document document) throws Exception { // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) throw new IllegalArgumentException("Not multipart content!"); FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List<FileItem> items = GenericUtils.cast(upload.parseRequest(request)); // Process the uploaded items handleFormFields(request); for (FileItem item : items) { doUpload(request, document, item); } }
private Collection<Part> parseMultipartWithCommonsFileUpload(HttpServletRequest request) throws IOException { if (sharedFileItemFactory.get() == null) { // Not a big deal if two threads actually set this up DiskFileItemFactory fileItemFactory = new DiskFileItemFactory( 1 << 16, (File) servletContext.getAttribute("javax.servlet.context.tempdir")); fileItemFactory.setFileCleaningTracker( FileCleanerCleanup.getFileCleaningTracker(servletContext)); sharedFileItemFactory.compareAndSet(null, fileItemFactory); } try { return new ServletFileUpload(sharedFileItemFactory.get()).parseRequest(request) .stream().map(FileItemPart::new).collect(Collectors.toList()); } catch (FileUploadException e) { throw new IOException(e.getMessage()); } }
public Map<String, Object> map(HttpServletRequest request) { ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); upload.setSizeMax(20 * 1024); upload.setFileSizeMax(10 * 1024); List<FileItem> items; try { items = upload.parseRequest(request); } catch (FileUploadException e) { throw new RequestMappingException("", e); } return items.stream().map(item -> { String key = item.getFieldName(); if (item.isFormField()) { String value = item.getString(); return new SimpleKeyValue<String, Object>(key, value); } else { return new SimpleKeyValue<String, Object>(key, item); } }).collect(Collectors.toMap( SimpleKeyValue::getKey, SimpleKeyValue::getValue )); }
/** * Basic constructor that takes the request object and saves it to be used by the subsequent * methods * * @param request * HttpServletRequest object originating from the user request. */ @SuppressWarnings("unchecked") public VariablesBase(HttpServletRequest request) { if (request == null) { // logging exception to obtain stack trace to pinpoint the cause log4j.warn("Creating a VariablesBase with a null request", new Exception()); this.session = new HttpSessionWrapper(); this.isMultipart = false; } else { this.session = request.getSession(true); this.httpRequest = request; this.isMultipart = ServletFileUpload.isMultipartContent(new ServletRequestContext(request)); if (isMultipart) { DiskFileItemFactory factory = new DiskFileItemFactory(); // factory.setSizeThreshold(yourMaxMemorySize); // factory.setRepositoryPath(yourTempDirectory); ServletFileUpload upload = new ServletFileUpload(factory); // upload.setSizeMax(yourMaxRequestSize); try { items = upload.parseRequest(request); } catch (Exception ex) { ex.printStackTrace(); } } } }
/** * extracts attachments from the http request. * * @param httpRequest * request containing attachments DefaultMultipartHttpServletRequest is supported * @param request * {@link Request} * @return ids of extracted attachments * @throws IOException * throws exception if problems during attachments accessing occurred * @throws FileUploadException * Exception. * @throws AttachmentIsEmptyException * Thrown, when the attachment is of zero size. * @throws AuthorizationException * in case there is no authenticated user */ private List<AttachmentResource> extractAttachments(HttpServletRequest httpRequest, Request request) throws FileUploadException, IOException, AttachmentIsEmptyException, AuthorizationException { List<AttachmentResource> result = new ArrayList<>(); if (httpRequest.getContentType().startsWith(AttachmentResourceHelper.MULTIPART_FORM_DATA)) { FileItemFactory factory = new DiskFileItemFactory(); FileUpload upload = new FileUpload(factory); List<FileItem> items = upload.parseRequest(new ServletRequestContext(httpRequest)); for (FileItem file : items) { if (!file.isFormField()) { AttachmentTO attachmentTo = new AttachmentStreamTO(file.getInputStream(), AttachmentStatus.UPLOADED); AttachmentResourceHelper.assertAttachmentSize(file.getContentType(), file.getSize(), false); attachmentTo.setMetadata(new ContentMetadata()); attachmentTo.getMetadata().setFilename(getFileName(file.getName())); attachmentTo.getMetadata().setContentSize(file.getSize()); result.add(persistAttachment(request, attachmentTo)); } } } return result; }
/** * extracts attachments from the http request. * * @param httpRequest * request containing attachments DefaultMultipartHttpServletRequest is supported * @param request * {@link Request} * @return ids of extracted attachments * @throws MaxLengthReachedException * attachment size is to large * @throws IOException * throws exception if problems during attachments accessing occurred * @throws FileUploadException * Exception. * @throws AttachmentIsEmptyException * Thrown, when the attachment is of zero size. * @throws AuthorizationException * in case there is no authenticated user */ private List<AttachmentResource> extractAttachments(HttpServletRequest httpRequest, Request request) throws MaxLengthReachedException, FileUploadException, IOException, AttachmentIsEmptyException, AuthorizationException { List<AttachmentResource> result = new ArrayList<AttachmentResource>(); if (httpRequest.getContentType().startsWith(AttachmentResourceHelper.MULTIPART_FORM_DATA)) { FileItemFactory factory = new DiskFileItemFactory(); FileUpload upload = new FileUpload(factory); List<FileItem> items = upload.parseRequest(new ServletRequestContext(httpRequest)); for (FileItem file : items) { if (!file.isFormField()) { AttachmentTO attachmentTo = new AttachmentStreamTO(file.getInputStream(), AttachmentStatus.UPLOADED); AttachmentResourceHelper.assertAttachmentSize(file.getContentType(), file.getSize(), false); attachmentTo.setMetadata(new ContentMetadata()); attachmentTo.getMetadata().setFilename(getFileName(file.getName())); attachmentTo.getMetadata().setContentSize(file.getSize()); result.add(persistAttachment(request, attachmentTo)); } } } return result; }
/** * extracts attachments from the http request. * * @param httpRequest * request containing attachments DefaultMultipartHttpServletRequest is supported * @param request * {@link Request} * @return ids of extracted attachments * @throws MaxLengthReachedException * attachment size is to large * @throws IOException * throws exception if problems during attachments accessing occurred * @throws FileUploadException * Exception. * @throws AuthorizationException * in case there is no authenticated user */ private List<AttachmentResource> extractAttachments(HttpServletRequest httpRequest, Request request) throws MaxLengthReachedException, FileUploadException, IOException, AuthorizationException { List<AttachmentResource> result = new ArrayList<AttachmentResource>(); if (httpRequest.getContentType().startsWith(AttachmentResourceHelper.MULTIPART_FORM_DATA)) { FileItemFactory factory = new DiskFileItemFactory(); FileUpload upload = new FileUpload(factory); List<FileItem> items = upload.parseRequest(new ServletRequestContext(httpRequest)); for (FileItem file : items) { if (!file.isFormField()) { AttachmentTO attachmentTo = new AttachmentStreamTO(file.getInputStream(), AttachmentStatus.UPLOADED); AttachmentResourceHelper.assertAttachmentSize(file.getContentType(), file.getSize(), false); attachmentTo.setMetadata(new ContentMetadata()); attachmentTo.getMetadata().setFilename(getFileName(file.getName())); attachmentTo.getMetadata().setContentSize(file.getSize()); result.add(persistAttachment(request, attachmentTo)); } } } return result; }
/** * extracts attachments from the http request. * * @param httpRequest * request containing attachments DefaultMultipartHttpServletRequest is supported * @param request * {@link Request} * @return ids of extracted attachments * @throws MaxLengthReachedException * attachment size is to large * @throws IOException * throws exception if problems during attachments accessing occurred * @throws FileUploadException * Exception. * @throws AuthorizationException * in case there is no authenticated user */ private List<AttachmentResource> extractAttachments(HttpServletRequest httpRequest, Request request) throws MaxLengthReachedException, FileUploadException, IOException, AuthorizationException { List<AttachmentResource> result = new ArrayList<AttachmentResource>(); if (httpRequest.getContentType().startsWith(AttachmentResourceHelper.MULTIPART_FORM_DATA)) { FileItemFactory factory = new DiskFileItemFactory(); FileUpload upload = new FileUpload(factory); List<FileItem> items = upload.parseRequest(new ServletRequestContext(httpRequest)); for (FileItem file : items) { if (!file.isFormField()) { AttachmentTO attachmentTo = new AttachmentStreamTO(file.getInputStream(), AttachmentStatus.UPLOADED); AttachmentResourceHelper.checkAttachmentSize(file); attachmentTo.setMetadata(new ContentMetadata()); attachmentTo.getMetadata().setFilename(getFileName(file.getName())); attachmentTo.getMetadata().setContentSize(file.getSize()); result.add(persistAttachment(request, attachmentTo)); } } } return result; }
private InputStream getInputStreamFromRequest(HttpServletRequest request) { InputStream inputStream=null; DiskFileItemFactory dff = new DiskFileItemFactory(); try { ServletFileUpload sfu = new ServletFileUpload(dff); FileItemIterator fii = sfu.getItemIterator(request); while (fii.hasNext()) { FileItemStream item = fii.next(); // 普通参数存储 if (!item.isFormField()) { // 只保留一个 if (inputStream == null) { inputStream = item.openStream(); return inputStream; } } } } catch (Exception e) { } return inputStream; }
private void handleFileUpload(PoseidonRequest request, HttpServletRequest httpRequest) throws IOException { // If uploaded file size is more than 10KB, will be stored in disk DiskFileItemFactory factory = new DiskFileItemFactory(); File repository = new File(FILE_UPLOAD_TMP_DIR); if (repository.exists()) { factory.setRepository(repository); } // Currently we don't impose max file size at container layer. Apps can impose it by checking FileItem // Apps also have to delete tmp file explicitly (if at all it went to disk) ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> fileItems = null; try { fileItems = upload.parseRequest(httpRequest); } catch (FileUploadException e) { throw new IOException(e); } for (FileItem fileItem : fileItems) { String name = fileItem.getFieldName(); if (fileItem.isFormField()) { request.setAttribute(name, new String[] { fileItem.getString() }); } else { request.setAttribute(name, fileItem); } } }
/** * This method returns FileItem handler out of file field in HTTP request * * @param req * @return FileItem * @throws IOException * @throws FileUploadException */ @SuppressWarnings("unchecked") public static FileItem getFileItem(HttpServletRequest req) throws IOException, FileUploadException { DiskFileItemFactory factory = new DiskFileItemFactory(); /* * we can increase the in memory size to hold the file data but its * inefficient so ignoring to factory.setSizeThreshold(20*1024); */ ServletFileUpload sFileUpload = new ServletFileUpload(factory); List<FileItem> items = sFileUpload.parseRequest(req); for (FileItem item : items) { if (!item.isFormField()) { return item; } } throw new FileUploadException("File field not found"); }
/*** * Simplest way of handling files that are uploaded from form. Just put them * as name-value pair into service data. This is useful ONLY if the files * are reasonably small. * * @param req * @param data * data in which */ public void simpleExtract(HttpServletRequest req, ServiceData data) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { /** * ServerFileUpload still deals with raw types. we have to have * workaround that */ List<?> list = upload.parseRequest(req); if (list != null) { for (Object item : list) { if (item instanceof FileItem) { FileItem fileItem = (FileItem) item; data.addValue(fileItem.getFieldName(), fileItem.getString()); } else { Spit.out("Servlet Upload retruned an item that is not a FileItem. Ignorinig that"); } } } } catch (FileUploadException e) { Spit.out(e); data.addError("Error while parsing form data. " + e.getMessage()); } }
private void processUpload(Exchange exchange) throws Exception { logger.debug("Begin import:"+ exchange.getIn().getHeaders()); if(exchange.getIn().getBody()!=null){ logger.debug("Body class:"+ exchange.getIn().getBody().getClass()); }else{ logger.debug("Body class is null"); } //logger.debug("Begin import:"+ exchange.getIn().getBody()); MediaType mediaType = exchange.getIn().getHeader(Exchange.CONTENT_TYPE, MediaType.class); InputRepresentation representation = new InputRepresentation((InputStream) exchange.getIn().getBody(), mediaType); logger.debug("Found MIME:"+ mediaType+", length:"+exchange.getIn().getHeader(Exchange.CONTENT_LENGTH, Integer.class)); //make a reply Json reply = Json.read("{\"files\": []}"); Json files = reply.at("files"); try { List<FileItem> items = new RestletFileUpload(new DiskFileItemFactory()).parseRepresentation(representation); logger.debug("Begin import files:"+items); for (FileItem item : items) { if (!item.isFormField()) { InputStream inputStream = item.getInputStream(); Path destination = Paths.get(Util.getConfigProperty(STATIC_DIR)+Util.getConfigProperty(MAP_DIR)+item.getName()); logger.debug("Save import file:"+destination); long len = Files.copy(inputStream, destination, StandardCopyOption.REPLACE_EXISTING); Json f = Json.object(); f.set("name",item.getName()); f.set("size",len); files.add(f); install(destination); } } } catch (FileUploadException | IOException e) { logger.error(e.getMessage(),e); } exchange.getIn().setBody(reply); }
/** * @param request * @param response * @return docAction (add or delete) * @throws ServletException */ protected List<FileItem> getMultiPartFileItems(HttpServletRequest request, HttpServletResponse response) throws ServletException { boolean isMultipart = ServletFileUpload.isMultipartContent(request); List<FileItem> items = null; try { if (isMultipart) { DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); items = uploadHandler.parseRequest(request); } } catch (Exception ex) { LOG.error("Error in getting the Reading the File:", ex); } return items; }
private ArrayList<File> extractBagFilesFromRequest(HttpServletRequest req, HttpServletResponse res) throws Exception { File targetDir = null; try { File file = null; DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1 MB Iterator items = new ServletFileUpload(fileItemFactory).parseRequest(req).iterator(); while (items.hasNext()) { FileItem item = (FileItem) items.next(); file = new File(FileUtils.getTempDirectory(), item.getName()); item.write(file); } targetDir = compressUtils.extractZippedBagFile(file.getAbsolutePath(), null); LOG.info("extractedBagFileLocation " + targetDir); } catch (IOException e) { LOG.error("IOException", e); sendResponseBag(res, e.getMessage(), "failure"); } catch (FormatHelper.UnknownFormatException unknownFormatException) { LOG.error("unknownFormatException", unknownFormatException); sendResponseBag(res, unknownFormatException.getMessage(), "failure"); } return compressUtils.getAllFilesList(targetDir); }
private ArrayList<File> extractBagFilesFromRequest(HttpServletRequest req, HttpServletResponse res) throws Exception { File targetDir = null; try { File file = null; DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1 MB Iterator items = new ServletFileUpload(fileItemFactory).parseRequest(req).iterator(); while (items.hasNext()) { FileItem item = (FileItem) items.next(); file = new File(FileUtils.getTempDirectory(), item.getName()); item.write(file); } targetDir = compressUtils.extractZippedBagFile(file.getAbsolutePath(), extractFilePath); LOG.info("extractedBagFileLocation " + targetDir); } catch (IOException e) { LOG.error("IOException", e); // sendResponseBag(res, e.getMessage(), "failure"); } catch (FormatHelper.UnknownFormatException unknownFormatException) { LOG.error("unknownFormatException", unknownFormatException); // sendResponseBag(res, unknownFormatException.getMessage(), "failure"); } return compressUtils.getAllFilesList(targetDir); }
private ArrayList<File> extractBagFilesFromRequest(@Context HttpServletRequest req, @Context HttpServletResponse res) throws Exception { File targetDir = null; try { File file = null; DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1 MB Iterator items = new ServletFileUpload(fileItemFactory).parseRequest(req).iterator(); while (items.hasNext()) { FileItem item = (FileItem) items.next(); LOG.info("item Name = " + item.getName() + " ; content type = " + item.getContentType()); file = new File(FileUtils.getTempDirectory(), item.getName()); item.write(file); } targetDir = compressUtils.extractZippedBagFile(file.getAbsolutePath(), null); LOG.info("extractedBagFileLocation " + targetDir); } catch (IOException e) { LOG.error("IOException", e); sendResponseBag(res, e.getMessage(), "failure"); } catch (FormatHelper.UnknownFormatException unknownFormatException) { LOG.error("unknownFormatException", unknownFormatException); sendResponseBag(res, unknownFormatException.getMessage(), "failure"); } return compressUtils.getAllFilesList(targetDir); }
public void parse(MultipartRequestCallback callback) throws IOException, FileUploadException, StatusServletException { if (!ServletFileUpload.isMultipartContent(request)) { LOGGER.error("Request content is not multipart."); throw new StatusServletException(Response.SC_PRECONDITION_FAILED); } final FileItemIterator iterator = new ServletFileUpload(new DiskFileItemFactory()).getItemIterator(request); while (iterator.hasNext()) { // Gets the first HTTP request element. final FileItemStream item = iterator.next(); if (item.isFormField()) { final String value = Streams.asString(item.openStream(), "UTF-8"); properties.put(item.getFieldName(), value); } else if(callback != null) { callback.onInputStream(item.openStream(), item.getFieldName(), item.getContentType()); } } }
/** * Sets up the given {@link org.apache.commons.httpclient.methods.PostMethod} to send the same multipart POST data * as was sent in the given {@link HttpServletRequest} * * @param postMethodProxyRequest The {@link org.apache.commons.httpclient.methods.PostMethod} that we are configuring to send a * multipart POST request * @param httpServletRequest The {@link HttpServletRequest} that contains the multipart * POST data to be sent via the {@link org.apache.commons.httpclient.methods.PostMethod} */ @SuppressWarnings("unchecked") public static void handleMultipartPost( EntityEnclosingMethod postMethodProxyRequest, HttpServletRequest httpServletRequest, DiskFileItemFactory diskFileItemFactory) throws ServletException { // TODO: this function doesn't set any history data try { // just pass back the binary data InputStreamRequestEntity ire = new InputStreamRequestEntity(httpServletRequest.getInputStream()); postMethodProxyRequest.setRequestEntity(ire); postMethodProxyRequest.setRequestHeader(STRING_CONTENT_TYPE_HEADER_NAME, httpServletRequest.getHeader(STRING_CONTENT_TYPE_HEADER_NAME)); } catch (Exception e) { throw new ServletException(e); } }
public Map<String, FileItem> getMultipartContent() throws FileUploadException, IllegalAccessException { if (!ServletFileUpload.isMultipartContent(request)) throw new IllegalAccessException(); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); Map<String, FileItem> result = new HashMap<String, FileItem>(); @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(request); for (FileItem fi : items) { result.put(fi.getFieldName(), fi); } return result; }
/** Process file upload */ private void processFileUpload(HttpRequest request, File uploadDir, String id) throws Exception { FileItemFactory factory = new DiskFileItemFactory(Config.THRESHOLD_UPLOAD, uploadDir); HttpServFileUpload fileUpload = new HttpServFileUpload(factory); fileUpload.setProgressListener(new MyProgressListener(id)); List<FileItem> fileItems = fileUpload.parseRequest(new HttpServRequestContext(request)); Iterator<FileItem> iter = fileItems.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) { processFormField(item); } else { processUploadedFile(item, uploadDir); } } }
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(4096); factory.setRepository(tempPathFile); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(4194304); // 设置最大文件尺寸,这里是4MB List<FileItem> items = upload.parseRequest(request);// 得到所有的文件 Iterator<FileItem> i = items.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); String fileName = fi.getName(); if (fileName != null) { File fullFile = new File(fi.getName()); File savedFile = new File(uploadPath, fullFile.getName()); fi.write(savedFile); } } } catch (Exception e) { e.printStackTrace(); } }
public HashMap getItems(HttpServletRequest request) throws ServiceException{ HashMap itemMap=null; try { String tempPath = System.getProperty("java.io.tmpdir"); FileItemFactory factory = new DiskFileItemFactory(4096,new File(tempPath)); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(1000000); List fileItems = upload.parseRequest(request); Iterator iter = fileItems.iterator(); itemMap=new HashMap(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { itemMap.put(item.getFieldName(), item.getString()); } else { itemMap.put(item.getFieldName(), item); } } } catch (Exception e) { e.printStackTrace(); throw ServiceException.FAILURE("FileUploadHandler.getItems", e); } return itemMap; }
/** * This function gets the fileItem from the form * * @param items the list of fields sent to this servlet * @return the imgItem if not found it returns null */ private FileItem getImgFileItem(final HttpServletRequest request) throws FileUploadException { // Create a factory for disk-based file items final FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler final ServletFileUpload upload = new ServletFileUpload(factory); final List< ? > items = upload.parseRequest(request); // get the items sent by the form FileItem fileItem = null; final Iterator< ? > iter = items.iterator(); // iterate over the items and if the required field is found break the loop while (iter.hasNext()) { fileItem = (FileItem) iter.next(); if (fileItem.isFormField() == false) { break; } } return fileItem; }
@Override public HSSFSheet uploadExcel(HttpServletRequest request) throws IOException, FileUploadException { ServletFileUpload fileupload = new ServletFileUpload( new DiskFileItemFactory()); fileupload.setSizeMax(1024 * 1024 * 10); @SuppressWarnings("unchecked") List<FileItem> fileitems = fileupload.parseRequest(request); InputStream inputStream = null; for (FileItem fileitem : fileitems) { if (!fileitem.isFormField()) { inputStream = fileitem.getInputStream(); break; } } HSSFWorkbook workbook = new HSSFWorkbook(inputStream); return workbook.getSheetAt(0); }