List of usage examples for org.apache.commons.fileupload FileItemStream isFormField
boolean isFormField();
FileItem
instance represents a simple form field. From source file:org.kuali.kfs.sys.web.servlet.BatchFileUploadServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { checkAuthorization(request);/*from ww w. j ava 2 s . c o m*/ ServletFileUpload upload = new ServletFileUpload(); String destPath = null; String fileName = null; String tempDir = System.getProperty("java.io.tmpdir"); // Parse the request try { FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); fileName = item.getName(); LOG.info("Processing Item: " + item.getFieldName()); if (item.isFormField()) { if (item.getFieldName().equals("uploadDir")) { Reader str = new InputStreamReader(item.openStream()); StringWriter sw = new StringWriter(); char buf[] = new char[100]; int len; while ((len = str.read(buf)) > 0) { sw.write(buf, 0, len); } destPath = sw.toString(); } } else { InputStream stream = item.openStream(); fileName = item.getName(); LOG.info("Uploading to Directory: " + tempDir); // Process the input stream FileOutputStream fos = new FileOutputStream(new File(tempDir, fileName)); BufferedOutputStream bos = new BufferedOutputStream(fos, 1024 * 1024); byte buf[] = new byte[10240]; int len; while ((len = stream.read(buf)) > 0) { bos.write(buf, 0, len); } bos.close(); stream.close(); } } LOG.info("Copying to Directory: " + destPath); if (!getBatchDirectories().contains(destPath)) { new File(tempDir, fileName).delete(); throw new RuntimeException("Illegal Attempt to upload to an unauthorized path: '" + destPath + "'"); } BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File(tempDir, fileName))); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(destPath, fileName)), 1024 * 1024); byte buf[] = new byte[10240]; int len; while ((len = bis.read(buf)) > 0) { bos.write(buf, 0, len); } bos.close(); bis.close(); } catch (FileUploadException ex) { LOG.error("Problem Uploading file", ex); } if (fileName != null) { request.setAttribute("message", "Successfully uploaded " + fileName + " to " + destPath); } else { request.setAttribute("message", "Upload Failed"); } doGet(request, response); }
From source file:org.kuali.student.core.document.ui.server.upload.UploadServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { UploadStatus status = new UploadStatus(); request.getSession().setAttribute(request.getParameter("uploadId"), status); try {/*from w w w.j a v a 2 s . co m*/ ServletFileUpload upload = new ServletFileUpload(); upload.setProgressListener( new DocumentProgressListener(request.getParameter("uploadId"), request.getSession())); FileItemIterator iter = upload.getItemIterator(request); DocumentInfo info = new DocumentInfo(); boolean fileError = false; int currentItem = 0; while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { String value = Streams.asString(stream); if (name.equals("documentDescription")) { RichTextInfo text = new RichTextInfo(); text.setPlain(value); info.setDescr(text); } } else { String fullFileName = item.getName(); if (fullFileName != null) { String filename = FilenameUtils.getName(fullFileName); FileStatus fileStatus = new FileStatus(); fileStatus.setFileName(filename); status.getFileStatusList().add(currentItem, fileStatus); DocumentBinaryInfo bInfo = new DocumentBinaryInfo(); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; while (true) { int read = stream.read(buffer); if (read == -1) { break; } else { bytes.write(buffer, 0, read); fileStatus.setProgress(fileStatus.getProgress() + read); } } bytes.flush(); fileStatus.setStatus(FileTransferStatus.UPLOAD_FINISHED); bInfo.setBinary(new String(Base64.encodeBase64(bytes.toByteArray()))); info.setDocumentBinary(bInfo); info.setStateKey(DtoState.ACTIVE.toString()); info.setFileName(filename); int extSeperator = filename.lastIndexOf("."); info.setName(filename.substring(0, extSeperator)); //FIXME Probably temporary solution for type on document info String type = "documentType." + filename.substring(extSeperator + 1).toLowerCase(); info.setTypeKey(type); } else { //No file specified error status.setStatus(UploadTransferStatus.ERROR); } } if (info.getDescr() != null && info.getDocumentBinary() != null && info.getType() != null) { //FileStatus fileStatus = status.getFileStatusMap().get(info.getFileName()); FileStatus fileStatus = status.getFileStatusList().get(currentItem); try { DocumentInfo createdDoc = documentService.createDocument(info.getTypeKey(), "documentCategory.proposal", info, ContextUtils.getContextInfo()); fileStatus.setStatus(FileTransferStatus.COMMIT_FINISHED); if (createdDoc != null) { status.getCreatedDocIds().add(createdDoc.getId()); fileStatus.setDocId(createdDoc.getId()); } RefDocRelationInfo relationInfo = new RefDocRelationInfo(); relationInfo.setStateKey(DtoState.ACTIVE.toString()); relationInfo.setDescr(info.getDescr()); relationInfo.setRefObjectId(request.getParameter("referenceId")); relationInfo.setRefObjectTypeKey(request.getParameter("refObjectTypeKey")); relationInfo.setTitle(info.getFileName()); relationInfo.setDocumentId(createdDoc.getId()); relationInfo.setType(request.getParameter("refDocRelationTypeKey")); documentService.createRefDocRelation(relationInfo.getRefObjectTypeKey(), relationInfo.getRefObjectId(), relationInfo.getDocumentId(), relationInfo.getTypeKey(), relationInfo, ContextUtils.getContextInfo()); } catch (Exception e) { fileError = true; LOG.error("Exception occurred", e); fileStatus.setStatus(FileTransferStatus.ERROR); } info = new DocumentInfo(); currentItem++; } } if (fileError) { status.setStatus(UploadTransferStatus.ERROR); } else { status.setStatus(UploadTransferStatus.COMMIT_FINISHED); } } catch (Exception e) { status.setStatus(UploadTransferStatus.ERROR); LOG.error("Exception occurred", e); } }
From source file:org.kurento.repository.internal.http.RepositoryHttpServlet.java
private void uploadMultipart(HttpServletRequest req, HttpServletResponse resp, OutputStream repoItemOutputStrem) throws IOException { log.debug("Multipart detected"); ServletFileUpload upload = new ServletFileUpload(); try {//from ww w .j a va2 s. c o m // Parse the request FileItemIterator iter = upload.getItemIterator(req); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); try (InputStream stream = item.openStream()) { if (item.isFormField()) { // TODO What to do with this? log.debug("Form field {} with value {} detected.", name, Streams.asString(stream)); } else { // TODO Must we support multiple files uploading? log.debug("File field {} with file name detected.", name, item.getName()); log.debug("Start to receive bytes (estimated bytes)", Integer.toString(req.getContentLength())); int bytes = IOUtils.copy(stream, repoItemOutputStrem); resp.setStatus(SC_OK); log.debug("Bytes received: {}", Integer.toString(bytes)); } } } } catch (FileUploadException e) { throw new IOException(e); } }
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 {/* w w w . j ava 2s. co 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.nema.medical.mint.server.controller.JobsController.java
public void handleUpload(HttpServletRequest request, File jobFolder, List<File> files, Map<String, String> params) throws IOException, FileUploadException { byte buf[] = new byte[32 * 1024]; int fileCount = 0; LOG.info("creating local files"); // Parse the request ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter;/*from w w w . j a va2 s . co m*/ iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream in = item.openStream(); if (item.isFormField()) { String value = Streams.asString(in); LOG.debug("found form field " + name + " = " + value); params.put(name, value); } else { File file; // special handling for first file - must be metadata! if (files.isEmpty()) { String filename = item.getName(); LOG.info("loading metadata from " + filename); outer: { for (String extension : supportedMetadataExtensions) { if (filename.endsWith(extension)) { filename = "metadata" + extension; break outer; } } //At this point, no proper filename has been established. Last resort, use content type! String contentType = item.getContentType(); if ("text/xml".equals(contentType)) { filename = "metadata.xml"; } else if ("application/octet-stream".equals(contentType)) { filename = "metadata.gpb"; } else { // dump out and write the content... will fail later LOG.error("unable to determine metadata type for " + item.getName()); filename = "metadata.dat"; } } file = new File(jobFolder, filename); } else { final String msgPartName = item.getFieldName(); try { if (!msgPartName.startsWith("binary")) { throw new Exception(); } final String itemIdStr = msgPartName.substring("binary".length()); final int itemId = Integer.parseInt(itemIdStr); file = new File(jobFolder, String.format("%d.dat", itemId)); } catch (final Exception e) { throw new IOException("Invalid message part name for binary data: '" + msgPartName + "'; must start with 'binary', followed by a number"); } } if (file.exists()) { throw new IOException("File for message part already exists: '" + file.getName() + "'"); } FileOutputStream out = null; out = new FileOutputStream(file); try { while (true) { int len = in.read(buf); if (len < 0) break; out.write(buf, 0, len); } } finally { if (out != null) { out.close(); files.add(file); fileCount++; } } } } LOG.info("created " + fileCount + " files."); }
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 ww . j a v a2 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 {//w w w.java 2s. c o m 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.onecmdb.ui.gwt.desktop.server.command.ChangeUploadCommand.java
private void getFileItem(HttpServletRequest request) throws FileUploadException, IOException { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { throw new IllegalArgumentException("Not multipart..."); }// w w w. j a v a 2 s . c o m ServletFileUpload upload = new ServletFileUpload(); List<String> mdrEntries = new ArrayList<String>(); // Parse the request FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { System.out.println("Form field " + name + " with value " + Streams.asString(stream) + " detected."); } else { System.out.println("File field " + name + " with file name " + item.getName() + " detected."); // Process the input stream } String mdrEntry = handleInput(name, stream); mdrEntries.add(mdrEntry); } commitContent(mdrEntries); }
From source file:org.onecmdb.ui.gwt.desktop.server.servlet.ContentServiceServlet.java
private void getFileItem(HttpServletRequest request, File root) throws FileUploadException, IOException { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { throw new IllegalArgumentException("Not multipart..."); }// w ww .ja va2 s .c o m ServletFileUpload upload = new ServletFileUpload(); // Parse the request FileItemIterator iter = upload.getItemIterator(request); String fileName = null; String path = null; while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); System.out.println("Name=" + item.getName()); if (item.isFormField()) { String value = Streams.asString(stream); System.out.println("FormField " + name + "=" + value); if (name.equals("name")) { fileName = value; } if (name.equals("path")) { path = value; } } else { System.out.println("File field " + name + " with file name " + item.getName() + " detected."); File output = new File(root, path + "/" + fileName); System.out.println("Write upload to " + output.getPath()); IOUtil.copyCompletely(stream, new FileOutputStream(output)); } } }
From source file:org.opencastproject.fileupload.rest.FileUploadRestService.java
@POST @Produces(MediaType.APPLICATION_XML)//from w w w .j a v a 2 s. com @Path("job/{jobID}") @RestQuery(name = "newjob", description = "Appends the next chunk of data to the file on the server.", pathParameters = { @RestParameter(description = "The ID of the upload job", isRequired = false, name = "jobID", type = RestParameter.Type.STRING) }, restParameters = { @RestParameter(description = "The number of the current chunk", isRequired = false, name = "chunknumber", type = RestParameter.Type.STRING), @RestParameter(description = "The payload", isRequired = false, name = "filedata", type = RestParameter.Type.FILE) }, reponses = { @RestResponse(description = "the chunk data was successfully appended to file on server", responseCode = HttpServletResponse.SC_OK), @RestResponse(description = "the upload job was not found", responseCode = HttpServletResponse.SC_NOT_FOUND), @RestResponse(description = "the request was malformed", responseCode = HttpServletResponse.SC_BAD_REQUEST) }, returnDescription = "The XML representation of the updated upload job") public Response postPayload(@PathParam("jobID") String jobId, @Context HttpServletRequest request) { try { if (!ServletFileUpload.isMultipartContent(request)) { // make sure request is "multipart/form-data" throw new FileUploadException("Request is not of type multipart/form-data"); } if (uploadService.hasJob(jobId)) { // testing for existence of job here already so we can generate a 404 early long chunkNum = 0; FileUploadJob job = uploadService.getJob(jobId); ServletFileUpload upload = new ServletFileUpload(); for (FileItemIterator iter = upload.getItemIterator(request); iter.hasNext();) { FileItemStream item = iter.next(); if (item.isFormField()) { String name = item.getFieldName(); if (REQUESTFIELD_CHUNKNUM.equalsIgnoreCase(name)) { chunkNum = Long.parseLong(Streams.asString(item.openStream())); } } else if (REQUESTFIELD_DATA.equalsIgnoreCase(item.getFieldName())) { uploadService.acceptChunk(job, chunkNum, item.openStream()); return Response.ok(job).build(); } } throw new FileUploadException("No payload!"); } else { log.warn("Upload job not found: " + jobId); return Response.status(Response.Status.NOT_FOUND).build(); } } catch (FileUploadException e) { log.error(e.getMessage(), e); return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build(); } catch (Exception e) { log.error(e.getMessage(), e); return Response.serverError().entity(buildUnexpectedErrorMessage(e)).build(); } }