org.apache.commons.fileupload.FileItemStream Java Examples
The following examples show how to use
org.apache.commons.fileupload.FileItemStream.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WorkbenchRequest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
private Map<String, String> getMultipartParameterMap() throws RepositoryException, IOException, FileUploadException { Map<String, String> parameters = new HashMap<>(); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(this); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); if ("content".equals(name)) { content = item.openStream(); contentFileName = item.getName(); break; } else { parameters.put(name, firstLine(item)); } } return parameters; }
Example #2
Source File: CloudStorageHelper.java From getting-started-java with Apache License 2.0 | 6 votes |
/** * Uploads a file to Google Cloud Storage to the bucket specified in the BUCKET_NAME * environment variable, appending a timestamp to end of the uploaded filename. */ @SuppressWarnings("deprecation") public String uploadFile(FileItemStream fileStream, final String bucketName) throws IOException, ServletException { checkFileExtension(fileStream.getName()); DateTimeFormatter dtf = DateTimeFormat.forPattern("-YYYY-MM-dd-HHmmssSSS"); DateTime dt = DateTime.now(DateTimeZone.UTC); String dtString = dt.toString(dtf); final String fileName = fileStream.getName() + dtString; // the inputstream is closed by default, so we don't need to close it here BlobInfo blobInfo = storage.create( BlobInfo .newBuilder(bucketName, fileName) // Modify access list to allow all users with link to read file .setAcl(new ArrayList<>(Arrays.asList(Acl.of(User.ofAllUsers(), Role.READER)))) .build(), fileStream.openStream()); // return the public download link return blobInfo.getMediaLink(); }
Example #3
Source File: CloudStorageHelper.java From getting-started-java with Apache License 2.0 | 6 votes |
/** * Uploads a file to Google Cloud Storage to the bucket specified in the BUCKET_NAME * environment variable, appending a timestamp to end of the uploaded filename. */ public String uploadFile(FileItemStream fileStream, final String bucketName) throws IOException, ServletException { checkFileExtension(fileStream.getName()); DateTimeFormatter dtf = DateTimeFormat.forPattern("-YYYY-MM-dd-HHmmssSSS"); DateTime dt = DateTime.now(DateTimeZone.UTC); String dtString = dt.toString(dtf); final String fileName = fileStream.getName() + dtString; // the inputstream is closed by default, so we don't need to close it here @SuppressWarnings("deprecation") BlobInfo blobInfo = storage.create( BlobInfo .newBuilder(bucketName, fileName) // Modify access list to allow all users with link to read file .setAcl(new ArrayList<>(Arrays.asList(Acl.of(User.ofAllUsers(), Role.READER)))) .build(), fileStream.openStream()); logger.log(Level.INFO, "Uploaded file {0} as {1}", new Object[]{ fileStream.getName(), fileName}); // return the public download link return blobInfo.getMediaLink(); }
Example #4
Source File: CloudStorageHelper.java From getting-started-java with Apache License 2.0 | 6 votes |
/** * Uploads a file to Google Cloud Storage to the bucket specified in the BUCKET_NAME environment * variable, appending a timestamp to end of the uploaded filename. */ public String uploadFile(FileItemStream fileStream, final String bucketName) throws IOException, ServletException { checkFileExtension(fileStream.getName()); System.out.println("FileStream name: " + fileStream.getName() + "\nBucket name: " + bucketName); DateTimeFormatter dtf = DateTimeFormat.forPattern("-YYYY-MM-dd-HHmmssSSS"); DateTime dt = DateTime.now(DateTimeZone.UTC); String dtString = dt.toString(dtf); final String fileName = fileStream.getName() + dtString; // the inputstream is closed by default, so we don't need to close it here @SuppressWarnings("deprecation") BlobInfo blobInfo = storage.create( BlobInfo.newBuilder(bucketName, fileName) // Modify access list to allow all users with link to read file .setAcl(new ArrayList<>(Arrays.asList(Acl.of(User.ofAllUsers(), Role.READER)))) .build(), fileStream.openStream()); logger.log( Level.INFO, "Uploaded file {0} as {1}", new Object[] {fileStream.getName(), fileName}); // return the public download link return blobInfo.getMediaLink(); }
Example #5
Source File: MultipartStream.java From restcommander with Apache License 2.0 | 6 votes |
/** * Returns the next byte in the stream. * @return The next byte in the stream, as a non-negative * integer, or -1 for EOF. * @throws IOException An I/O error occurred. */ public int read() throws IOException { if (closed) { throw new FileItemStream.ItemSkippedException(); } if (available() == 0) { if (makeAvailable() == 0) { return -1; } } ++total; int b = buffer[head++]; if (b >= 0) { return b; } return b + BYTE_POSITIVE_OFFSET; }
Example #6
Source File: MultipartStream.java From restcommander with Apache License 2.0 | 6 votes |
/** * Reads bytes into the given buffer. * @param b The destination buffer, where to write to. * @param off Offset of the first byte in the buffer. * @param len Maximum number of bytes to read. * @return Number of bytes, which have been actually read, * or -1 for EOF. * @throws IOException An I/O error occurred. */ public int read(byte[] b, int off, int len) throws IOException { if (closed) { throw new FileItemStream.ItemSkippedException(); } if (len == 0) { return 0; } int res = available(); if (res == 0) { res = makeAvailable(); if (res == 0) { return -1; } } res = Math.min(res, len); System.arraycopy(buffer, head, b, off, res); head += res; total += res; return res; }
Example #7
Source File: FunctionalTest.java From nio-multipart with Apache License 2.0 | 6 votes |
void dumpFileIterator(final FileItemIterator fileItemIterator){ int partIndex = 0; try { log.info("-- COMMONS FILE UPLOAD --"); while (fileItemIterator.hasNext()) { log.info("-- Part " + partIndex++); FileItemStream fileItemStream = fileItemIterator.next(); FileItemHeaders fileItemHeaders = fileItemStream.getHeaders(); Iterator<String> headerNames = fileItemHeaders.getHeaderNames(); while(headerNames.hasNext()){ String headerName = headerNames.next(); log.info("Header: " + headerName+ ": " + Joiner.on(',').join(fileItemHeaders.getHeaders(headerName))); } log.info("Body:\n" + IOUtils.toString(fileItemStream.openStream())); } log.info("-- ------------------- --"); }catch (Exception e){ log.error("Error dumping the FileItemIterator", e); } }
Example #8
Source File: MultipartStream.java From restcommander with Apache License 2.0 | 6 votes |
/** * Skips the given number of bytes. * @param bytes Number of bytes to skip. * @return The number of bytes, which have actually been * skipped. * @throws IOException An I/O error occurred. */ public long skip(long bytes) throws IOException { if (closed) { throw new FileItemStream.ItemSkippedException(); } int av = available(); if (av == 0) { av = makeAvailable(); if (av == 0) { return 0; } } long res = Math.min(av, bytes); head += res; return res; }
Example #9
Source File: CloudStorageHelper.java From getting-started-java with Apache License 2.0 | 6 votes |
/** * Uploads a file to Google Cloud Storage to the bucket specified in the BUCKET_NAME * environment variable, appending a timestamp to end of the uploaded filename. */ public String uploadFile(FileItemStream fileStream, final String bucketName) throws IOException, ServletException { checkFileExtension(fileStream.getName()); DateTimeFormatter dtf = DateTimeFormat.forPattern("-YYYY-MM-dd-HHmmssSSS"); DateTime dt = DateTime.now(DateTimeZone.UTC); String dtString = dt.toString(dtf); final String fileName = fileStream.getName() + dtString; // the inputstream is closed by default, so we don't need to close it here @SuppressWarnings("deprecation") BlobInfo blobInfo = storage.create( BlobInfo .newBuilder(bucketName, fileName) // Modify access list to allow all users with link to read file .setAcl(new ArrayList<>(Arrays.asList(Acl.of(User.ofAllUsers(), Role.READER)))) .build(), fileStream.openStream()); // return the public download link return blobInfo.getMediaLink(); }
Example #10
Source File: MultipartController.java From nio-multipart with Apache License 2.0 | 6 votes |
/** * <p> Example of parsing the multipart request using commons file upload. In this case the parsing happens in blocking io. * * @param request The {@code HttpServletRequest} * @return The {@code VerificationItems} * @throws Exception if an exception happens during the parsing */ @RequestMapping(value = "/blockingio/fileupload/multipart", method = RequestMethod.POST) public @ResponseBody VerificationItems blockingIoMultipart(final HttpServletRequest request) throws Exception { assertRequestIsMultipart(request); final ServletFileUpload servletFileUpload = new ServletFileUpload(); final FileItemIterator fileItemIterator = servletFileUpload.getItemIterator(request); final VerificationItems verificationItems = new VerificationItems(); Metadata metadata = null; while (fileItemIterator.hasNext()){ FileItemStream fileItemStream = fileItemIterator.next(); if (METADATA_FIELD_NAME.equals(fileItemStream.getFieldName())){ if (metadata != null){ throw new IllegalStateException("Found more than one metadata field"); } metadata = unmarshalMetadata(fileItemStream.openStream()); }else { VerificationItem verificationItem = buildVerificationItem(fileItemStream.openStream(), fileItemStream.getFieldName(), fileItemStream.isFormField()); verificationItems.getVerificationItems().add(verificationItem); } } processVerificationItems(verificationItems, metadata, false, request.getHeader(VERIFICATION_CONTROL_HEADER_NAME)); return verificationItems; }
Example #11
Source File: MiscHandle.java From httplite with Apache License 2.0 | 6 votes |
private String handleMultipart(RecordedRequest request) { RecordedUpload upload = new RecordedUpload(request); Exception exception; try { Map<String,String> params = new HashMap<>(); FileItemIterator iter = upload.getItemIterator(); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { String value = Streams.asString(stream); System.out.println("Form field " + name + " with value " + value + " detected."); params.put(name,value); } else { System.out.println("File field " + name + " with file name " + item.getName() + " detected."); params.put(name, "file->"+item.getName()); } } return "Multipart:"+JSON.toJSONString(params); } catch (Exception e) { exception = e; } return "Multipart:error->"+exception; }
Example #12
Source File: StreamReceiverHandler.java From flow with Apache License 2.0 | 6 votes |
private boolean handleMultipartFileUploadFromInputStream(VaadinSession session, VaadinRequest request, StreamReceiver streamReceiver, StateNode owner) throws IOException { boolean success = true; long contentLength = request.getContentLength(); // Parse the request FileItemIterator iter; try { iter = getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); boolean itemSuccess = handleStream(session, streamReceiver, owner, contentLength, item); success = success && itemSuccess; } } catch (FileUploadException e) { success = false; getLogger().warn("File upload failed.", e); } return success; }
Example #13
Source File: MultipartStream.java From actframework with Apache License 2.0 | 6 votes |
/** * Skips the given number of bytes. * @param bytes Number of bytes to skip. * @return The number of bytes, which have actually been * skipped. * @throws IOException An I/O error occurred. */ public long skip(long bytes) throws IOException { if (closed) { throw new FileItemStream.ItemSkippedException(); } int av = available(); if (av == 0) { av = makeAvailable(); if (av == 0) { return 0; } } long res = Math.min(av, bytes); head += res; return res; }
Example #14
Source File: MicroflowService.java From RestServices with Apache License 2.0 | 6 votes |
private void parseMultipartData(RestServiceRequest rsr, IMendixObject argO, JSONObject data) throws IOException, FileUploadException { boolean hasFile = false; for(FileItemIterator iter = servletFileUpload.getItemIterator(rsr.request); iter.hasNext();) { FileItemStream item = iter.next(); if (!item.isFormField()){ //This is the file(?!) if (!isFileSource) { RestServices.LOGPUBLISH.warn("Received request with binary data but input argument isn't a filedocument. Skipping. At: " + rsr.request.getRequestURL().toString()); continue; } if (hasFile) RestServices.LOGPUBLISH.warn("Received request with multiple files. Only one is supported. At: " + rsr.request.getRequestURL().toString()); hasFile = true; Core.storeFileDocumentContent(rsr.getContext(), argO, determineFileName(item), item.openStream()); } else data.put(item.getFieldName(), IOUtils.toString(item.openStream())); } }
Example #15
Source File: FilesApiServiceImpl.java From multiapps-controller with Apache License 2.0 | 6 votes |
private List<FileEntry> uploadFiles(HttpServletRequest request, String spaceGuid, String namespace) throws FileUploadException, IOException, FileStorageException { List<FileEntry> uploadedFiles = new ArrayList<>(); FileItemIterator fileItemIterator = createFileIterator(request); while (fileItemIterator.hasNext()) { FileItemStream item = fileItemIterator.next(); if (item.isFormField()) { continue; // ignore simple (non-file) form fields } try (InputStream in = item.openStream()) { FileEntry entry = fileService.addFile(spaceGuid, namespace, item.getName(), in); uploadedFiles.add(entry); } } return uploadedFiles; }
Example #16
Source File: MultipartStreamCopy.java From dcs-sdk-java with Apache License 2.0 | 6 votes |
/** * Skips the given number of bytes. * * @param bytes Number of bytes to skip. * @return The number of bytes, which have actually been * skipped. * @throws IOException An I/O error occurred. */ @Override public long skip(long bytes) throws IOException { if (closed) { throw new FileItemStream.ItemSkippedException(); } int av = available(); if (av == 0) { av = makeAvailable(); if (av == 0) { return 0; } } long res = Math.min(av, bytes); head += res; return res; }
Example #17
Source File: MultipartStreamCopy.java From dcs-sdk-java with Apache License 2.0 | 6 votes |
/** * Reads bytes into the given buffer. * * @param b The destination buffer, where to write to. * @param off Offset of the first byte in the buffer. * @param len Maximum number of bytes to read. * @return Number of bytes, which have been actually read, * or -1 for EOF. * @throws IOException An I/O error occurred. */ @Override public int read(byte[] b, int off, int len) throws IOException { if (closed) { throw new FileItemStream.ItemSkippedException(); } if (len == 0) { return 0; } int res = available(); if (res == 0) { res = makeAvailable(); if (res == 0) { return -1; } } res = Math.min(res, len); System.arraycopy(buffer, head, b, off, res); head += res; total += res; return res; }
Example #18
Source File: MultipartStreamCopy.java From dcs-sdk-java with Apache License 2.0 | 6 votes |
/** * Returns the next byte in the stream. * * @return The next byte in the stream, as a non-negative * integer, or -1 for EOF. * @throws IOException An I/O error occurred. */ @Override public int read() throws IOException { if (closed) { throw new FileItemStream.ItemSkippedException(); } if (available() == 0 && makeAvailable() == 0) { return -1; } ++total; int b = buffer[head++]; if (b >= 0) { return b; } return b + BYTE_POSITIVE_OFFSET; }
Example #19
Source File: MultipartStream.java From actframework with Apache License 2.0 | 6 votes |
/** * Reads bytes into the given buffer. * @param b The destination buffer, where to write to. * @param off Offset of the first byte in the buffer. * @param len Maximum number of bytes to read. * @return Number of bytes, which have been actually read, * or -1 for EOF. * @throws IOException An I/O error occurred. */ public int read(byte[] b, int off, int len) throws IOException { if (closed) { throw new FileItemStream.ItemSkippedException(); } if (len == 0) { return 0; } int res = available(); if (res == 0) { res = makeAvailable(); if (res == 0) { return -1; } } res = Math.min(res, len); System.arraycopy(buffer, head, b, off, res); head += res; total += res; return res; }
Example #20
Source File: MultipartStream.java From actframework with Apache License 2.0 | 6 votes |
/** * Returns the next byte in the stream. * @return The next byte in the stream, as a non-negative * integer, or -1 for EOF. * @throws IOException An I/O error occurred. */ public int read() throws IOException { if (closed) { throw new FileItemStream.ItemSkippedException(); } if (available() == 0) { if (makeAvailable() == 0) { return -1; } } ++total; int b = buffer[head++]; if (b >= 0) { return b; } return b + BYTE_POSITIVE_OFFSET; }
Example #21
Source File: UploadFileStorageService.java From actframework with Apache License 2.0 | 5 votes |
private ISObject _store(FileItemStream fileItemStream) throws IOException { String filename = fileItemStream.getName(); String key = newKey(filename); File tmpFile = getFile(key); InputStream input = fileItemStream.openStream(); ThresholdingByteArrayOutputStream output = new ThresholdingByteArrayOutputStream(inMemoryCacheThreshold, tmpFile); IO.copy(input, output); ISObject retVal; if (output.exceedThreshold) { retVal = getFull(key); } else { int size = output.written; if (0 == size) { return null; } byte[] buf = output.buf(); retVal = SObject.of(key, buf, size); } if (S.notBlank(filename)) { retVal.setFilename(filename); } String contentType = fileItemStream.getContentType(); if (null != contentType) { retVal.setContentType(contentType); } return retVal; }
Example #22
Source File: UploadCommandExecutor.java From elfinder-2.x-servlet with BSD 2-Clause "Simplified" License | 5 votes |
public Part(long start, long size, FileItemStream fileItemStream) { super(); this._start = start; this._size = size; this._content = fileItemStream; }
Example #23
Source File: RepositoryHttpServlet.java From kurento-java with Apache License 2.0 | 5 votes |
private void uploadMultipart(HttpServletRequest req, HttpServletResponse resp, OutputStream repoItemOutputStrem) throws IOException { log.debug("Multipart detected"); ServletFileUpload upload = new ServletFileUpload(); try { // 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); } }
Example #24
Source File: UploadFileStorageService.java From actframework with Apache License 2.0 | 5 votes |
public static ISObject store(FileItemStream fileItemStream, App app) { UploadFileStorageService ss = app.uploadFileStorageService(); try { return ss._store(fileItemStream); } catch (IOException e) { throw E.ioException(e); } }
Example #25
Source File: MultipartPayloadProvider.java From camunda-bpm-platform with Apache License 2.0 | 5 votes |
protected void parseRequest(MultipartFormData multipartFormData, FileUpload fileUpload, RestMultipartRequestContext requestContext) { try { FileItemIterator itemIterator = fileUpload.getItemIterator(requestContext); while (itemIterator.hasNext()) { FileItemStream stream = itemIterator.next(); multipartFormData.addPart(new FormPart(stream)); } } catch (Exception e) { throw new RestException(Status.BAD_REQUEST, e, "multipart/form-data cannot be processed"); } }
Example #26
Source File: UploadCommandExecutor.java From elfinder-2.x-servlet with BSD 2-Clause "Simplified" License | 5 votes |
private void processUpload(MultipleUploadItems uploads, FileWriter fw) throws IOException { for (FileItemStream fis : uploads.items("upload[]")) { fw.createAndSave(fis.getName(), fis.openStream()); } }
Example #27
Source File: MultipleUploadItems.java From elfinder-2.x-servlet with BSD 2-Clause "Simplified" License | 5 votes |
/** * find items with given form field name * * @param fieldName * @return */ public List<FileItemStream> items(String fieldName) { List<FileItemStream> filteredItems = new ArrayList<FileItemStream>(); for (FileItemStream fis : _items) { if (fis.getFieldName().equals(fieldName)) filteredItems.add(fis); } return filteredItems; }
Example #28
Source File: MultipleUploadItems.java From elfinder-2.x-servlet with BSD 2-Clause "Simplified" License | 5 votes |
public void addItemProxy(final FileItemStream item) throws IOException { InputStream stream = item.openStream(); //ByteArrayOutputStream os = new ByteArrayOutputStream(); //create a temp source final File source = File.createTempFile("elfinder_upload_", "", _tempDir); FileOutputStream os = new FileOutputStream(source); IOUtils.copy(stream, os); os.close(); //final byte[] bs = os.toByteArray(); stream.close(); _logger.debug(String.format("saving item: %s", source.getCanonicalPath())); addItem((FileItemStream) Proxy.newProxyInstance(this.getClass() .getClassLoader(), new Class[]{FileItemStream.class, Finalizable.class}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if ("openStream".equals(method.getName())) { //return new ByteArrayInputStream(bs); return new FileInputStream(source); } if ("finalize".equals(method.getName())) { source.delete(); _logger.debug(String.format("removing item: %s", source.getCanonicalPath())); return null; } return method.invoke(item, args); } })); }
Example #29
Source File: MultipleUploadItems.java From elfinder-2.x-servlet with BSD 2-Clause "Simplified" License | 5 votes |
public static void finalize(HttpServletRequest request) { MultipleUploadItems mui = loadFrom(request); if (mui != null) { for (FileItemStream fis : mui.items()) { if (fis instanceof Finalizable) { ((Finalizable) fis).finalize(); } } } }
Example #30
Source File: Uploader.java From jeecg with Apache License 2.0 | 5 votes |
private void parseParams() { DiskFileItemFactory dff = new DiskFileItemFactory(); try { ServletFileUpload sfu = new ServletFileUpload(dff); sfu.setSizeMax(this.maxSize); sfu.setHeaderEncoding(Uploader.ENCODEING); FileItemIterator fii = sfu.getItemIterator(this.request); while (fii.hasNext()) { FileItemStream item = fii.next(); // 普通参数存储 if (item.isFormField()) { this.params.put(item.getFieldName(), this.getParameterValue(item.openStream())); } else { // 只保留一个 if (this.inputStream == null) { this.inputStream = item.openStream(); this.originalName = item.getName(); return; } } } } catch (Exception e) { this.state = this.errorInfo.get("UNKNOWN"); } }