List of usage examples for org.apache.commons.fileupload.util Streams asString
public static String asString(InputStream pStream, String pEncoding) throws IOException
From source file:org.duracloud.duradmin.spaces.controller.ContentItemUploadController.java
@RequestMapping(value = "/spaces/content/upload", method = RequestMethod.POST) public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { try {/*from ww w . j a va 2s . c o m*/ log.debug("handling request..."); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(request); String spaceId = null; String storeId = null; String contentId = null; List<ContentItem> results = new ArrayList<ContentItem>(); while (iter.hasNext()) { FileItemStream item = iter.next(); if (item.isFormField()) { String value = Streams.asString(item.openStream(), "UTF-8"); if (item.getFieldName().equals("spaceId")) { log.debug("setting spaceId: {}", value); spaceId = value; } else if (item.getFieldName().equals("storeId")) { storeId = value; } else if (item.getFieldName().equals("contentId")) { contentId = value; } } else { log.debug("setting fileStream: {}", item); if (StringUtils.isBlank(spaceId)) { throw new IllegalArgumentException("space id required."); } ContentItem ci = new ContentItem(); if (StringUtils.isBlank(contentId)) { contentId = item.getName(); } ci.setContentId(contentId); ci.setSpaceId(spaceId); ci.setStoreId(storeId); ci.setContentMimetype(item.getContentType()); ContentStore contentStore = contentStoreManager.getContentStore(ci.getStoreId()); ContentItemUploadTask task = new ContentItemUploadTask(ci, contentStore, item.openStream(), request.getUserPrincipal().getName()); task.execute(); ContentItem result = new ContentItem(); Authentication auth = (Authentication) SecurityContextHolder.getContext().getAuthentication(); SpaceUtil.populateContentItem(ContentItemController.getBaseURL(request), result, ci.getSpaceId(), ci.getContentId(), contentStore, auth); results.add(result); contentId = null; } } return new ModelAndView("javascriptJsonView", "results", results); } catch (Exception ex) { ex.printStackTrace(); throw ex; } }
From source file:org.eclipse.scout.rt.ui.html.json.UploadRequestHandler.java
protected void readUploadData(HttpServletRequest httpReq, long maxSize, Map<String, String> uploadProperties, List<BinaryResource> uploadResources) throws FileUploadException, IOException { ServletFileUpload upload = new ServletFileUpload(); upload.setHeaderEncoding(StandardCharsets.UTF_8.name()); upload.setSizeMax(maxSize);/*from www .j av a2s .c o m*/ for (FileItemIterator it = upload.getItemIterator(httpReq); it.hasNext();) { FileItemStream item = it.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { // Handle non-file fields (interpreted as properties) uploadProperties.put(name, Streams.asString(stream, StandardCharsets.UTF_8.name())); } else { // Handle files String filename = item.getName(); if (StringUtility.hasText(filename)) { String[] parts = StringUtility.split(filename, "[/\\\\]"); filename = parts[parts.length - 1]; } String contentType = item.getContentType(); byte[] content = IOUtility.getContent(stream); // Info: we cannot set the charset property for uploaded files here, because we simply don't know it. // the only thing we could do is to guess the charset (encoding) by reading the byte contents of // uploaded text files (for binary file types the encoding is not relevant). However: currently we // do not set the charset at all. uploadResources.add(new BinaryResource(filename, contentType, content)); } } }
From source file:org.ejbca.ui.web.HttpUpload.java
/** * Creates a new upload state and receives all file and parameter data. * This constructor can only be called once per request. * //from w w w.ja v a 2s .c o m * Use getParameterMap() and getFileMap() on the new object to access the data. * * @param request The servlet request object. * @param fileFields The names of the file fields to receive uploaded data from. * @param maxbytes Maximum file size. * @throws IOException if there are network problems, etc. * @throws FileUploadException if the request is invalid. */ @SuppressWarnings("unchecked") // Needed in some environments, and detected as unnecessary in others. Do not remove! public HttpUpload(HttpServletRequest request, String[] fileFields, int maxbytes) throws IOException, FileUploadException { if (ServletFileUpload.isMultipartContent(request)) { final Map<String, ArrayList<String>> paramTemp = new HashMap<String, ArrayList<String>>(); fileMap = new HashMap<String, byte[]>(); final ServletFileUpload upload = new ServletFileUpload(); final FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { final FileItemStream item = iter.next(); final String name = item.getFieldName(); if (item.isFormField()) { ArrayList<String> values = paramTemp.get(name); if (values == null) { values = new ArrayList<String>(); paramTemp.put(name, values); } values.add(Streams.asString(item.openStream(), request.getCharacterEncoding())); } else if (ArrayUtils.contains(fileFields, name)) { byte[] data = getFileBytes(item, maxbytes); if (data != null && data.length > 0) { fileMap.put(name, data); } } } // Convert to String,String[] map parameterMap = new ParameterMap(); for (Entry<String, ArrayList<String>> entry : paramTemp.entrySet()) { final ArrayList<String> values = entry.getValue(); final String[] valuesArray = new String[values.size()]; parameterMap.put(entry.getKey(), values.toArray(valuesArray)); } } else { parameterMap = new ParameterMap(request.getParameterMap()); fileMap = new HashMap<String, byte[]>(); } }
From source file:org.jahia.tools.files.FileUpload.java
/** * Init the MultiPartReq object if it's actually null * * @exception IOException//w w w .ja va2 s .co m */ protected void init() throws IOException { params = new HashMap<String, List<String>>(); paramsContentType = new HashMap<String, String>(); files = new HashMap<String, DiskFileItem>(); filesByFieldName = new HashMap<String, DiskFileItem>(); parseQueryString(); if (checkSavePath(savePath)) { try { final ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(req); DiskFileItemFactory factory = null; while (iter.hasNext()) { FileItemStream item = iter.next(); InputStream stream = item.openStream(); if (item.isFormField()) { final String name = item.getFieldName(); final List<String> v; if (params.containsKey(name)) { v = params.get(name); } else { v = new ArrayList<String>(); params.put(name, v); } v.add(Streams.asString(stream, encoding)); paramsContentType.put(name, item.getContentType()); } else { if (factory == null) { factory = new DiskFileItemFactory(); factory.setSizeThreshold(1); factory.setRepository(new File(savePath)); } DiskFileItem fileItem = (DiskFileItem) factory.createItem(item.getFieldName(), item.getContentType(), item.isFormField(), item.getName()); try { Streams.copy(item.openStream(), fileItem.getOutputStream(), true); } catch (FileUploadIOException e) { throw (FileUploadException) e.getCause(); } catch (IOException e) { throw new IOFileUploadException("Processing of " + FileUploadBase.MULTIPART_FORM_DATA + " request failed. " + e.getMessage(), e); } final FileItemHeaders fih = item.getHeaders(); fileItem.setHeaders(fih); if (fileItem.getSize() > 0) { files.put(fileItem.getStoreLocation().getName(), fileItem); filesByFieldName.put(fileItem.getFieldName(), fileItem); } } } } catch (FileUploadException ioe) { logger.error("Error while initializing FileUpload class:", ioe); throw new IOException(ioe.getMessage()); } } else { logger.error("FileUpload::init storage path does not exists or can write"); throw new IOException("FileUpload::init storage path does not exists or cannot write"); } }
From source file:org.kimios.controller.UploadManager.java
private String startUploadFile(HttpServletRequest req) throws Exception { DiskFileItemFactory fp = new DiskFileItemFactory(); fp.setRepository(new File(ConfigurationManager.getValue(Config.DM_TMP_FILES_PATH))); ServletFileUpload sfu = new ServletFileUpload(fp); QProgressListener pp = new QProgressListener(uploads); sfu.setProgressListener(pp);//from www . j ava2s .c o m String uploadId = ""; String name = ""; String sec = ""; String metaValues = ""; String docTypeUid = ""; String action = ""; String documentUid = ""; //used for import String newVersion = ""; boolean isSecurityInherited = false; long folderUid = 0; String mimeType = ""; String extension = ""; FileItemIterator t = sfu.getItemIterator(req); while (t.hasNext()) { FileItemStream st = t.next(); if (st.isFormField()) { String tmpVal = Streams.asString(st.openStream(), "UTF-8"); log.debug(st.getFieldName() + " --> " + tmpVal); if (st.getFieldName().equalsIgnoreCase("actionUpload")) { action = tmpVal; } if (st.getFieldName().equalsIgnoreCase("newVersion")) { newVersion = tmpVal; } if (st.getFieldName().equalsIgnoreCase("documentUid")) { documentUid = tmpVal; } if (st.getFieldName().equalsIgnoreCase("UPLOAD_ID")) { uploadId = tmpVal; pp.setUploadId(uploadId); } if (st.getFieldName().equalsIgnoreCase("name")) { name = tmpVal; } if (st.getFieldName().equalsIgnoreCase("sec")) { sec = StringEscapeUtils.unescapeHtml(tmpVal); } if (st.getFieldName().equalsIgnoreCase("documentTypeUid")) { docTypeUid = tmpVal; } if (st.getFieldName().equalsIgnoreCase("metaValues")) { metaValues = StringEscapeUtils.unescapeHtml(tmpVal); } if (st.getFieldName().equalsIgnoreCase("folderUid")) { folderUid = Long.parseLong(tmpVal); } if (st.getFieldName().equalsIgnoreCase("inheritedPermissions")) { isSecurityInherited = (tmpVal != null && tmpVal.equalsIgnoreCase("on")); } } else { InputStream in = st.openStream(); mimeType = st.getContentType(); extension = st.getName().substring(st.getName().lastIndexOf('.') + 1); int transferChunkSize = Integer.parseInt(ConfigurationManager.getValue(Config.DM_CHUNK_SIZE)); if (action.equalsIgnoreCase("AddDocument")) { Document d = new Document(); d.setCreationDate(Calendar.getInstance()); d.setExtension(extension); d.setFolderUid(folderUid); d.setCheckedOut(false); d.setMimeType(mimeType); d.setName(name); d.setOwner(""); d.setUid(-1); long docUid = documentController.createDocument(sessionUid, d, isSecurityInherited); if (!isSecurityInherited) { securityController.updateDMEntitySecurities(sessionUid, docUid, 3, false, DMEntitySecuritiesParser.parseFromJson(sec, docUid, 3)); } fileTransferController.uploadFileFirstVersion(sessionUid, docUid, in, false); long documentTypeUid = -1; try { documentTypeUid = Long.parseLong(docTypeUid); } catch (Exception e) { } if (documentTypeUid > 0) { Map<Meta, String> mMetasValues = DMEntitySecuritiesParser .parseMetasValuesFromJson(sessionUid, metaValues, documentVersionController); String xmlMeta = XMLGenerators.getMetaDatasDocumentXMLDescriptor(mMetasValues, "MM/dd/yyyy"); documentVersionController.updateDocumentVersion(sessionUid, docUid, documentTypeUid, xmlMeta); } } else { if (action.equalsIgnoreCase("Import")) { documentController.checkoutDocument(sessionUid, Long.parseLong(documentUid)); fileTransferController.uploadFileNewVersion(sessionUid, Long.parseLong(documentUid), in, false); documentController.checkinDocument(sessionUid, Long.parseLong(documentUid)); } else if (action.equalsIgnoreCase("UpdateCurrent")) { documentController.checkoutDocument(sessionUid, Long.parseLong(documentUid)); fileTransferController.uploadFileUpdateVersion(sessionUid, Long.parseLong(documentUid), in, false); documentController.checkinDocument(sessionUid, Long.parseLong(documentUid)); } } } } return "{success: true}"; }
From source file:org.myjerry.web.multipart.StreamingMultipartResolver.java
public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException { // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(); upload.setFileSizeMax(maxUploadSize); String encoding = determineEncoding(request); Map<String, MultipartFile> multipartFiles = new HashMap<String, MultipartFile>(); Map<String, String[]> multipartParameters = new HashMap<String, String[]>(); // MultiValueMap multipartFiles = new MultiValueMap(); // Parse the request try {// ww w .jav a 2 s .c o m FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { String value = Streams.asString(stream, encoding); String[] curParam = (String[]) multipartParameters.get(name); if (curParam == null) { // simple form field multipartParameters.put(name, new String[] { value }); } else { // array of simple form fields String[] newParam = StringUtils.addStringToArray(curParam, value); multipartParameters.put(name, newParam); } } else { // Process the input stream MultipartFile file = new StreamingMultipartFile(item); multipartFiles.put(name, file); } } } catch (IOException e) { throw new MultipartException("something went wrong here", e); } catch (FileUploadException e) { throw new MultipartException("something went wrong here", e); } return new DefaultMultipartHttpServletRequest(request, multipartFiles, multipartParameters); }
From source file:org.olat.core.gui.components.form.flexible.impl.Form.java
/** * Internal helper to initialize the request parameter map an to temporary store the uploaded files when a multipart request is used. The files are stored to a * temporary location and a filehandle is added to the requestMultipartFiles map for later retrieval by the responsible FormItem. * /*from w w w.j a va 2 s . com*/ * @param ureq */ private void doInitRequestParameterAndMulipartData(UserRequest ureq) { // First fill parameter map either from multipart data or standard http request if (isMultipartEnabled() && ServletFileUpload.isMultipartContent(ureq.getHttpReq())) { long uploadSize = -1; // default unlimited // Limit size of complete upload form: upload size limit + 500k for // other input fields if (multipartUploadMaxSizeKB > -1) { uploadSize = (multipartUploadMaxSizeKB * 1024l * 1024l) + 512000l; } // Create a new file upload handler, use commons fileupload streaming // API to save files right to the tmp location ServletFileUpload uploadParser = new ServletFileUpload(); uploadParser.setSizeMax(uploadSize); // Parse the request try { FileItemIterator iter = uploadParser.getItemIterator(ureq.getHttpReq()); while (iter.hasNext()) { FileItemStream item = iter.next(); String itemName = item.getFieldName(); InputStream itemStream = item.openStream(); if (item.isFormField()) { // Normal form item // analog to ureq.getParameter in non-multipart mode String value = Streams.asString(itemStream, "UTF-8"); addRequestParameter(itemName, value); } else { // File item, store it to temp location String fileName = item.getName(); // Cleanup IE filenames that are absolute int slashpos = fileName.lastIndexOf("/"); if (slashpos != -1) fileName = fileName.substring(slashpos + 1); slashpos = fileName.lastIndexOf("\\"); if (slashpos != -1) fileName = fileName.substring(slashpos + 1); File tmpFile = new File(System.getProperty("java.io.tmpdir") + File.separator + "upload-" + CodeHelper.getGlobalForeverUniqueID()); try { FileUtils.save(itemStream, tmpFile); // Only save non-empty file transfers, ignore empty transfers // (e.g. already submitted in a previous form submit, not an error!) // Removing empty file check for now ... was introduced to cope with // browser trouble which probably is not there any more ... // so empty fileName means nothing selected in the file element // if (tmpFile.length() > 0) { if (fileName.length() > 0) { // a file was selected // Save file and also original file name requestMultipartFiles.put(itemName, tmpFile); requestMultipartFileNames.put(itemName, fileName); requestMultipartFileMimeTypes.put(itemName, item.getContentType()); } else { if (tmpFile.exists()) tmpFile.delete(); } } catch (OLATRuntimeException e) { // Could not save stream for whatever reason, cleanup temp file and delegate exception if (tmpFile.exists()) tmpFile.delete(); if (e.getCause() instanceof MalformedStreamException) { logWarn("Could not read uploaded file >" + fileName + "< from stream. Possibly an attempt to upload a directory instead of a file (happens on Mac)", e); return; } throw new OLATRuntimeException("Could not save uploaded file", e); } } } } catch (SizeLimitExceededException sizeLimitExceededException) { logError("Error while dispatching multipart form: file limit (" + uploadSize + ") exceeded", sizeLimitExceededException); requestError = REQUEST_ERROR_UPLOAD_LIMIT_EXCEEDED; } catch (IOException e) { logWarn("Error while dispatching multipart form: ioexception", e); requestError = REQUEST_ERROR_GENERAL; } catch (Exception e) { logError("Error while dispatching multipart form: general exception", e); requestError = REQUEST_ERROR_GENERAL; } } else { // Get parameters the standard way logDebug("Dispatching non-multipart form", null); Set<String> keys = ureq.getParameterSet(); for (String key : keys) { String[] values = ureq.getHttpReq().getParameterValues(key); if (values != null) { requestParams.put(key, values); } else { addRequestParameter(key, ureq.getParameter(key)); } } } }
From source file:org.olat.restapi.support.MultipartReader.java
private final void apache(HttpServletRequest request, long uploadLimit) { ServletFileUpload uploadParser = new ServletFileUpload(); uploadParser.setSizeMax((uploadLimit * 1024l) + 512000l); // Parse the request try {// ww w.j av a 2s . c om FileItemIterator iter = uploadParser.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String itemName = item.getFieldName(); InputStream itemStream = item.openStream(); if (item.isFormField()) { String value = Streams.asString(itemStream, "UTF-8"); fields.put(itemName, value); } else { // File item, store it to temp location filename = item.getName(); contentType = item.getContentType(); if (filename != null) { filename = UUID.randomUUID().toString().replace("-", "") + "_" + filename; } else { filename = "upload-" + UUID.randomUUID().toString().replace("-", ""); } file = new File(WebappHelper.getTmpDir(), filename); try { save(itemStream, file); } catch (Exception e) { log.error("", e); } } } } catch (Exception e) { log.error("", e); } }
From source file:org.sigmah.server.file.util.MultipartRequest.java
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); }// w w w .ja va 2 s. c om 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()); } } }
From source file:org.tangram.components.servlet.ServletRequestParameterAccess.java
/** * Weak visibility to avoid direct instanciation. */// w w w. ja v a 2 s .c o m @SuppressWarnings("unchecked") ServletRequestParameterAccess(HttpServletRequest request, long uploadFileMaxSize) { final String reqContentType = request.getContentType(); LOG.debug("() uploadFileMaxSize={} request.contentType={}", uploadFileMaxSize, reqContentType); if (StringUtils.isNotBlank(reqContentType) && reqContentType.startsWith("multipart/form-data")) { ServletFileUpload upload = new ServletFileUpload(); upload.setFileSizeMax(uploadFileMaxSize); try { for (FileItemIterator itemIterator = upload.getItemIterator(request); itemIterator.hasNext();) { FileItemStream item = itemIterator.next(); String fieldName = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { String[] value = parameterMap.get(item.getFieldName()); int i = 0; if (value == null) { value = new String[1]; } else { String[] newValue = new String[value.length + 1]; System.arraycopy(value, 0, newValue, 0, value.length); i = value.length; value = newValue; } // if value[i] = Streams.asString(stream, "UTF-8"); LOG.debug("() request parameter {}='{}'", fieldName, value[0]); parameterMap.put(item.getFieldName(), value); } else { try { LOG.debug("() item {} :{}", item.getName(), item.getContentType()); final byte[] bytes = IOUtils.toByteArray(stream); if (bytes.length > 0) { originalNames.put(fieldName, item.getName()); blobs.put(fieldName, bytes); } // if } catch (IOException ex) { LOG.error("()", ex); if (ex.getCause() instanceof FileUploadBase.FileSizeLimitExceededException) { throw new RuntimeException(ex.getCause().getMessage()); // NOPMD we want to lose parts of our stack trace! } // if } // try/catch } // if } // for } catch (FileUploadException | IOException ex) { LOG.error("()", ex); } // try/catch } else { parameterMap = request.getParameterMap(); } // if }