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); } }
/** * 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; }
/*** * 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()); } }
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); } } }
/** * Handles a file contained in the specified {@code request}. If you use * FileUpload, please make sure to add the needed dependencies, i.e. * {@code commons-fileupload} and {@code servlet-api} (later will be removed * in a newer version of the {@code commons-fileupload}. * * @param request * the request to handle the file upload from * @param factory * the {@code FileItemFactory} used to handle the request * * @return the {@code List} of loaded files * * @throws FileUploadException * if the file upload fails */ public static List<FileItem> handleFileUpload(final HttpRequest request, final FileItemFactory factory) throws FileUploadException { final List<FileItem> items; if (request instanceof HttpEntityEnclosingRequest && "POST".equals(request.getRequestLine().getMethod())) { // create the ServletFileUpload final FileUpload upload = new FileUpload(factory); final HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; items = upload.parseRequest(new RequestWrapper(entityRequest)); } else { items = new ArrayList<FileItem>(); } return items; }
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; }
public static ParsedRequest getStringParametersMap(HttpServletRequest request) throws FileUploadException { HashMap<String, String> textMap = new HashMap<>(); ParsedRequest parsedRequest = new ParsedRequest(textMap, null); try { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> uploadItems = upload.parseRequest(request); for (FileItem item : uploadItems) { String fieldName = item.getFieldName(); String value = item.getString(); textMap.put(fieldName, value); } } catch (Exception e) { loggerFactory.error(e); } return parsedRequest; }
public static ParsedRequest getParametersMap(HttpServletRequest request) throws FileUploadException { HashMap<String, String> textMap = new HashMap<>(); HashMap<String, File> fileMap = new HashMap<>(); ParsedRequest parsedRequest = new ParsedRequest(textMap, fileMap); try { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> uploadItems = upload.parseRequest(request); for (FileItem item : uploadItems) { String fieldName = item.getFieldName(); if (item.isFormField()) { String value = item.getString(); textMap.put(fieldName, value); } else { String filename = FilenameUtils.getName(item.getName()); InputStream fileContent = item.getInputStream(); File file = new File(ServerConsts.tempFileStore + "/" + filename); FileHelper.saveToFile(fileContent, file); fileMap.put(fieldName, file); } } } catch (Exception e) { loggerFactory.error(e); } return parsedRequest; }
@RequestMapping(method = RequestMethod.POST) protected ModelAndView handleRequestInternal(HttpServletRequest request) throws Exception { String username = securityService.getCurrentUsername(request); // Check that we have a file upload request. if (!ServletFileUpload.isMultipartContent(request)) { throw new Exception("Illegal request."); } Map<String, Object> map = new HashMap<String, Object>(); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<?> items = upload.parseRequest(request); // Look for file items. for (Object o : items) { FileItem item = (FileItem) o; if (!item.isFormField()) { String fileName = item.getName(); byte[] data = item.get(); if (StringUtils.isNotBlank(fileName) && data.length > 0) { createAvatar(fileName, data, username, map); } else { map.put("error", new Exception("Missing file.")); LOG.warn("Failed to upload personal image. No file specified."); } break; } } map.put("username", username); map.put("avatar", settingsService.getCustomAvatar(username)); return new ModelAndView("avatarUploadResult","model",map); }
@RequestMapping(method = RequestMethod.POST) protected String handlePost(RedirectAttributes redirectAttributes, HttpServletRequest request ) throws Exception { Map<String, Object> map = new HashMap<String, Object>(); try { if (ServletFileUpload.isMultipartContent(request)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<?> items = upload.parseRequest(request); for (Object o : items) { FileItem item = (FileItem) o; if ("file".equals(item.getFieldName()) && !StringUtils.isBlank(item.getName())) { if (item.getSize() > MAX_PLAYLIST_SIZE_MB * 1024L * 1024L) { throw new Exception("The playlist file is too large. Max file size is " + MAX_PLAYLIST_SIZE_MB + " MB."); } String playlistName = FilenameUtils.getBaseName(item.getName()); String fileName = FilenameUtils.getName(item.getName()); String format = StringUtils.lowerCase(FilenameUtils.getExtension(item.getName())); String username = securityService.getCurrentUsername(request); Playlist playlist = playlistService.importPlaylist(username, playlistName, fileName, item.getInputStream(), null); map.put("playlist", playlist); } } } } catch (Exception e) { map.put("error", e.getMessage()); } redirectAttributes.addFlashAttribute("model", map); return "redirect:importPlaylist"; }
@Override protected FileUpload newFileUpload(FileItemFactory fileItemFactory) { ServletFileUpload upload = new ServletFileUpload(fileItemFactory); upload.setSizeMax(-1); if (request != null) { // 注入监听 FileUploadProgressListener uploadProgressListener = new FileUploadProgressListener(); upload.setProgressListener(uploadProgressListener); request.getSession().setAttribute(C.UPLOAD_PROGRESS_LISTENER_KEY, uploadProgressListener); } return upload; }
/** * Parse file and save. * * @param request request. * @param saveDirectory save directory. * @throws Exception may be. */ private void processFileUpload(HttpRequest request, File saveDirectory) throws Exception { FileItemFactory factory = new DiskFileItemFactory(1024 * 1024, saveDirectory); HttpFileUpload fileUpload = new HttpFileUpload(factory); // Set upload process listener. // fileUpload.setProgressListener(new ProgressListener(){...}); List<FileItem> fileItems = fileUpload.parseRequest(new HttpUploadContext((HttpEntityEnclosingRequest) request)); for (FileItem fileItem : fileItems) { if (!fileItem.isFormField()) { // File param. // Attribute. // fileItem.getContentType(); // fileItem.getFieldName(); // fileItem.getName(); // fileItem.getSize(); // fileItem.getString(); File uploadedFile = new File(saveDirectory, fileItem.getName()); // 把流写到文件上。 fileItem.write(uploadedFile); } else { // General param. String key = fileItem.getName(); String value = fileItem.getString(); } } }
@Override protected FileUpload newFileUpload(FileItemFactory fileItemFactory) { return new ServletFileUpload() { @Override public List<FileItem> parseRequest(HttpServletRequest request) { if (request instanceof MultipartHttpServletRequest) { throw new IllegalStateException("Already a multipart request"); } List<FileItem> fileItems = new ArrayList<FileItem>(); MockFileItem fileItem1 = new MockFileItem( "field1", "type1", empty ? "" : "field1.txt", empty ? "" : "text1"); MockFileItem fileItem1x = new MockFileItem( "field1", "type1", empty ? "" : "field1.txt", empty ? "" : "text1"); MockFileItem fileItem2 = new MockFileItem( "field2", "type2", empty ? "" : "C:\\mypath/field2.txt", empty ? "" : "text2"); MockFileItem fileItem2x = new MockFileItem( "field2x", "type2", empty ? "" : "C:/mypath\\field2x.txt", empty ? "" : "text2"); MockFileItem fileItem3 = new MockFileItem("field3", null, null, "value3"); MockFileItem fileItem4 = new MockFileItem("field4", "text/html; charset=iso-8859-1", null, "value4"); MockFileItem fileItem5 = new MockFileItem("field4", null, null, "value5"); fileItems.add(fileItem1); fileItems.add(fileItem1x); fileItems.add(fileItem2); fileItems.add(fileItem2x); fileItems.add(fileItem3); fileItems.add(fileItem4); fileItems.add(fileItem5); return fileItems; } }; }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { assertTrue(ServletFileUpload.isMultipartContent(req)); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> items = upload.parseRequest(req); assertEquals(4, items.size()); FileItem item = items.get(0); assertTrue(item.isFormField()); assertEquals("name 1", item.getFieldName()); assertEquals("value 1", item.getString()); item = items.get(1); assertTrue(item.isFormField()); assertEquals("name 2", item.getFieldName()); assertEquals("value 2+1", item.getString()); item = items.get(2); assertTrue(item.isFormField()); assertEquals("name 2", item.getFieldName()); assertEquals("value 2+2", item.getString()); item = items.get(3); assertFalse(item.isFormField()); assertEquals("logo", item.getFieldName()); assertEquals("logo.jpg", item.getName()); assertEquals("image/jpeg", item.getContentType()); } catch (FileUploadException ex) { throw new ServletException(ex); } }
@Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { String username = securityService.getCurrentUsername(request); // Check that we have a file upload request. if (!ServletFileUpload.isMultipartContent(request)) { throw new Exception("Illegal request."); } Map<String, Object> map = new HashMap<String, Object>(); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<?> items = upload.parseRequest(request); // Look for file items. for (Object o : items) { FileItem item = (FileItem) o; if (!item.isFormField()) { String fileName = item.getName(); byte[] data = item.get(); if (StringUtils.isNotBlank(fileName) && data.length > 0) { createAvatar(fileName, data, username, map); } else { map.put("error", new Exception("Missing file.")); LOG.warn("Failed to upload personal image. No file specified."); } break; } } map.put("username", username); map.put("avatar", settingsService.getCustomAvatar(username)); ModelAndView result = super.handleRequestInternal(request, response); result.addObject("model", map); return result; }
@Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { Map<String, Object> map = new HashMap<String, Object>(); try { if (ServletFileUpload.isMultipartContent(request)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<?> items = upload.parseRequest(request); for (Object o : items) { FileItem item = (FileItem) o; if ("file".equals(item.getFieldName()) && !StringUtils.isBlank(item.getName())) { if (item.getSize() > MAX_PLAYLIST_SIZE_MB * 1024L * 1024L) { throw new Exception("The playlist file is too large. Max file size is " + MAX_PLAYLIST_SIZE_MB + " MB."); } String playlistName = FilenameUtils.getBaseName(item.getName()); String fileName = FilenameUtils.getName(item.getName()); String format = StringUtils.lowerCase(FilenameUtils.getExtension(item.getName())); String username = securityService.getCurrentUsername(request); Playlist playlist = playlistService.importPlaylist(username, playlistName, fileName, format, item.getInputStream(), null); map.put("playlist", playlist); } } } } catch (Exception e) { map.put("error", e.getMessage()); } ModelAndView result = super.handleRequestInternal(request, response); result.addObject("model", map); return result; }
private List<?> extractParameterList(final HttpServletRequest request) { List<?> parameters; try { FileItemFactory itemFactory = new DiskFileItemFactory(); parameters = new ServletFileUpload(itemFactory).parseRequest(request); } catch (FileUploadException e) { log.error("Unable to parse uploaded files", e); throw new RuntimeException("Unable to parse uploaded files", e); } return parameters; }
private static FileItemFactory getDefaultFileItemFactory(final int threshold) { final DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setFileCleaningTracker( new FileCleaningTracker() ); diskFileItemFactory.setSizeThreshold( threshold ); return diskFileItemFactory; }
/** * Constructor. * * @param request * The request */ public LazyInitializationFile( Request request, FileItemFactory fileItemFactory ) { super( new HashMap<String, Map<String, Object>>() ); this.request = request; fileUpload = new RestletFileUpload( fileItemFactory ); }
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // �ж��ϴ����Ƿ�����ļ� boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { // ��ȡ·�� String realpath = request.getSession().getServletContext().getRealPath("/files"); System.out.println(realpath); File dir = new File(realpath); if (!dir.exists()) dir.mkdirs(); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); try { // ����������� ��ʵ���� form����ÿ��input�ڵ� List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { // ����DZ� ����ÿ���� ��ӡ������̨ String name1 = item.getFieldName();// �õ�������������� String value = item.getString("UTF-8");// �õ�����ֵ System.out.println(name1 + "=" + value); } else { // ���ļ�д����ǰservlet����Ӧ��·�� item.write(new File(dir, System.currentTimeMillis() + item.getName().substring(item.getName().lastIndexOf(".")))); } } } catch (Exception e) { e.printStackTrace(); } } }
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // �ж��ϴ����Ƿ�����ļ� boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { // ��ȡ·�� String realpath = request.getSession().getServletContext() .getRealPath("/files"); System.out.println(realpath); File dir = new File(realpath); if (!dir.exists()) dir.mkdirs(); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); try { // ����������� ��ʵ���� form����ÿ��input�ڵ� List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { // ����DZ� ����ÿ���� ��ӡ������̨ String name1 = item.getFieldName();// �õ�������������� String value = item.getString("UTF-8");// �õ�����ֵ System.out.println(name1 + "=" + value); } else { // ���ļ�д����ǰservlet����Ӧ��·�� item.write(new File(dir, System.currentTimeMillis() + item.getName().substring( item.getName().lastIndexOf(".")))); } } } catch (Exception e) { e.printStackTrace(); } } }
/** * {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public void doPost(HttpServletRequest request, HttpServletResponse response) { try { HttpRequestHolder.setServletRequest(request); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); response.setContentType("text/xml"); ServletOutputStream out = response.getOutputStream(); for (FileItem item : items) { if (!item.isFormField()) { out.print("<resource"); IResourceBase uploadResource = new UploadResourceAdapter( "application/octet-stream", item); String resourceId = ResourceManager.getInstance().register( uploadResource); out.print(" id=\"" + resourceId); // Sometimes prevents the browser to parse back the result // out.print("\" name=\"" + HtmlHelper.escapeForHTML(item.getName())); out.println("\" />"); } } out.flush(); out.close(); } catch (Exception ex) { LOG.error("An unexpected error occurred while uploading the content.", ex); } finally { HttpRequestHolder.setServletRequest(null); } }
public HttpRequestServletImpl(HttpMethod httpMethod, HttpServletRequest request) throws IOException { this.request = request; this.httpMethod = httpMethod; if (ServletFileUpload.isMultipartContent(request)) { FileItemFactory fileItemFactory = new DiskFileItemFactory( DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD, new File(System.getProperty("java.io.tmpdir")) ); ServletFileUpload fileUpload = new ServletFileUpload(fileItemFactory); try { this.bodyParameters = fileUpload.parseParameterMap(request); } catch (FileUploadException e) { throw new IOException(e); } } else { if (request.getMethod().equals("POST") || request.getMethod().equals("PUT")) { String contentType = request.getHeader("Content-Type"); if (contentType != null && contentType.contains("application/x-www-form-urlencoded")) { this.bodyParameters = new HashMap<>(); String[] parameters = IOUtils.readStreamAsString(request.getInputStream()).split("&"); for (String parameter : parameters) { String[] keyVal = parameter.split("="); if (keyVal.length == 2) { String key = keyVal[0]; String value = URLDecoder.decode(keyVal[1], "UTF-8"); List<FileItem> items = new ArrayList<>(); items.add(new FormFileItem(key, value)); this.bodyParameters.put(key, items); } } } else { this.inputStream = request.getInputStream(); } } } this.queryParameters = request.getParameterMap(); }
@SuppressWarnings("unchecked") // commons-upload... private List<FileItem> getFileItems(final HttpServletRequest request) throws FileUploadException { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); return items; }
@Override protected FileUpload newFileUpload(FileItemFactory fileItemFactory) { return new ServletFileUpload() { @Override public List<FileItem> parseRequest(HttpServletRequest request) { if (request instanceof MultipartHttpServletRequest) { throw new IllegalStateException("Already a multipart request"); } List<FileItem> fileItems = new ArrayList<FileItem>(); MockFileItem fileItem1 = new MockFileItem( "field1", "type1", empty ? "" : "field1.txt", empty ? "" : "text1"); MockFileItem fileItem1x = new MockFileItem( "field1", "type1", empty ? "" : "field1.txt", empty ? "" : "text1"); MockFileItem fileItem2 = new MockFileItem( "field2", "type2", empty ? "" : "C:/field2.txt", empty ? "" : "text2"); MockFileItem fileItem2x = new MockFileItem( "field2x", "type2", empty ? "" : "C:\\field2x.txt", empty ? "" : "text2"); MockFileItem fileItem3 = new MockFileItem("field3", null, null, "value3"); MockFileItem fileItem4 = new MockFileItem("field4", "text/html; charset=iso-8859-1", null, "value4"); MockFileItem fileItem5 = new MockFileItem("field4", null, null, "value5"); fileItems.add(fileItem1); fileItems.add(fileItem1x); fileItems.add(fileItem2); fileItems.add(fileItem2x); fileItems.add(fileItem3); fileItems.add(fileItem4); fileItems.add(fileItem5); return fileItems; } }; }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { assertTrue(ServletFileUpload.isMultipartContent(req)); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List items = upload.parseRequest(req); assertEquals(4, items.size()); FileItem item = (FileItem) items.get(0); assertTrue(item.isFormField()); assertEquals("name 1", item.getFieldName()); assertEquals("value 1", item.getString()); item = (FileItem) items.get(1); assertTrue(item.isFormField()); assertEquals("name 2", item.getFieldName()); assertEquals("value 2+1", item.getString()); item = (FileItem) items.get(2); assertTrue(item.isFormField()); assertEquals("name 2", item.getFieldName()); assertEquals("value 2+2", item.getString()); item = (FileItem) items.get(3); assertFalse(item.isFormField()); assertEquals("logo", item.getFieldName()); assertEquals("logo.jpg", item.getName()); assertEquals("image/jpeg", item.getContentType()); } catch (FileUploadException ex) { throw new ServletException(ex); } }
private static List parseRequest(RequestContext requestContext) throws FileUploadException { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request return upload.parseRequest(requestContext); }