/** * 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; }
/** * 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; }
/** * 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; }
/** * Processes the FileItemStream as a Form Field. * * @param itemStream file item stream */ private void processFileItemStreamAsFormField(FileItemStream itemStream) { String fieldName = itemStream.getFieldName(); try { List<String> values; String fieldValue = Streams.asString(itemStream.openStream()); if (!parameters.containsKey(fieldName)) { values = new ArrayList<>(); parameters.put(fieldName, values); } else { values = parameters.get(fieldName); } values.add(fieldValue); } catch (IOException e) { LOG.warn("Failed to handle form field '{}'.", fieldName, e); } }
/** * Processes the FileItemStream as a file field. * * @param itemStream file item stream * @param location location */ private void processFileItemStreamAsFileField(FileItemStream itemStream, String location) { // Skip file uploads that don't have a file name - meaning that no file was selected. if (itemStream.getName() == null || itemStream.getName().trim().length() < 1) { LOG.debug("No file has been uploaded for the field: {}", itemStream.getFieldName()); return; } File file = null; try { // Create the temporary upload file. file = createTemporaryFile(itemStream.getName(), location); if (streamFileToDisk(itemStream, file)) { createFileInfoFromItemStream(itemStream, file); } } catch (IOException e) { if (file != null) { try { file.delete(); } catch (SecurityException se) { LOG.warn("Failed to delete '{}' due to security exception above.", file.getName(), se); } } } }
/** * Creates an internal <code>FileInfo</code> structure used to pass information * to the <code>FileUploadInterceptor</code> during the interceptor stack * invocation process. * * @param itemStream file item stream * @param file the file */ private void createFileInfoFromItemStream(FileItemStream itemStream, File file) { // gather attributes from file upload stream. String fileName = itemStream.getName(); String fieldName = itemStream.getFieldName(); // create internal structure FileInfo fileInfo = new FileInfo(file, itemStream.getContentType(), fileName); // append or create new entry. if (!fileInfos.containsKey(fieldName)) { List<FileInfo> infos = new ArrayList<>(); infos.add(fileInfo); fileInfos.put(fieldName, infos); } else { fileInfos.get(fieldName).add(fileInfo); } }
private Map<String, String> getRequestData(HttpServletRequest request) { Map<String, String> requestData = new HashMap<>(); ServletFileUpload upload = new ServletFileUpload(); try { FileItemIterator itemIterator = upload.getItemIterator(request); while (itemIterator.hasNext()) { FileItemStream item = itemIterator.next(); InputStream itemStream = item.openStream(); String value = Streams.asString(itemStream, CharEncoding.UTF_8); requestData.put(item.getFieldName(), value); } } catch (FileUploadException | IOException e) { LOGGER.error("Failed to process request", e); } return requestData; }
/** * <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; }
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); } }
/** * 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(); }
/** * 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(); }
/** * 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(); }
private InputStream getInputStreamFromRequest(HttpServletRequest request) { InputStream inputStream=null; DiskFileItemFactory dff = new DiskFileItemFactory(); try { ServletFileUpload sfu = new ServletFileUpload(dff); FileItemIterator fii = sfu.getItemIterator(request); while (fii.hasNext()) { FileItemStream item = fii.next(); // 普通参数存储 if (!item.isFormField()) { // 只保留一个 if (inputStream == null) { inputStream = item.openStream(); return inputStream; } } } } catch (Exception e) { } return inputStream; }
private ZipFile createZipFile(FileItemStream item) { ZipFile zipFile = null; try { File f = new File("zipFile"); InputStream inputStream = item.openStream(); OutputStream outputStream = new FileOutputStream(f); int len; byte[] buffer = new byte[1000000]; while ((len = inputStream.read(buffer, 0, buffer.length)) != -1) { outputStream.write(buffer, 0, len); } outputStream.close(); inputStream.close(); zipFile = new ZipFile(f); } catch (Exception e) { LOG.error(e.getMessage()); } return zipFile; }
@Override protected void execute(ElfinderStorage elfinderStorage, HttpServletRequest request, JSONObject json) throws Exception { List<FileItemStream> files = (List<FileItemStream>) request.getAttribute(FileItemStream.class.getName()); List<VolumeHandler> added = new ArrayList<>(); String target = request.getParameter(ElFinderConstants.ELFINDER_PARAMETER_TARGET); VolumeHandler parentDir = findTarget(elfinderStorage, target); for (FileItemStream file : files) { String fileName = file.getName(); VolumeHandler newFile = new VolumeHandler(parentDir, fileName); newFile.createFile(); InputStream is = file.openStream(); OutputStream os = newFile.openOutputStream(); IOUtils.copy(is, os); os.close(); is.close(); added.add(newFile); } json.put(ElFinderConstants.ELFINDER_JSON_RESPONSE_ADDED, buildJsonFilesArray(request, added)); }
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())); } }
/** * 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; }
/** * 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; }
/** * 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; }
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; 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; }
/** * Provides parsed email headers from the "headers" param in a multipart/form-data request. * <p> * Although SendGrid parses some headers for us, it doesn't parse "reply-to", so we need to do * this. Once we are doing it, it's easier to be consistent and use this as the sole source of * truth for information that originates in the headers. */ @Provides @Singleton InternetHeaders provideHeaders(FileItemIterator iterator) { try { while (iterator != null && iterator.hasNext()) { FileItemStream item = iterator.next(); // SendGrid sends us the headers in the "headers" param. if (item.getFieldName().equals("headers")) { try (InputStream stream = item.openStream()) { // SendGrid always sends headers in UTF-8 encoding. return new InternetHeaders(new ByteArrayInputStream( CharStreams.toString(new InputStreamReader(stream, UTF_8.name())).getBytes(UTF_8))); } } } } catch (MessagingException | FileUploadException | IOException e) { // If we fail parsing the headers fall through returning the empty header object below. } return new InternetHeaders(); // Parsing failed or there was no "headers" param. }
public void parse(MultipartRequestCallback callback) throws IOException, FileUploadException, StatusServletException { if (!ServletFileUpload.isMultipartContent(request)) { LOGGER.error("Request content is not multipart."); throw new StatusServletException(Response.SC_PRECONDITION_FAILED); } final FileItemIterator iterator = new ServletFileUpload(new DiskFileItemFactory()).getItemIterator(request); while (iterator.hasNext()) { // Gets the first HTTP request element. final FileItemStream item = iterator.next(); if (item.isFormField()) { final String value = Streams.asString(item.openStream(), "UTF-8"); properties.put(item.getFieldName(), value); } else if(callback != null) { callback.onInputStream(item.openStream(), item.getFieldName(), item.getContentType()); } } }
public void addItemProxy(final FileItemStream item) throws IOException { InputStream stream = item.openStream(); ByteArrayOutputStream os = new ByteArrayOutputStream(); IOUtils.copy(stream, os); final byte[] bs = os.toByteArray(); stream.close(); addItem((FileItemStream) Proxy.newProxyInstance(this.getClass() .getClassLoader(), new Class[] { FileItemStream.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 method.invoke(item, args); } })); }
private List<FileEntry> uploadFiles(HttpServletRequest request, String spaceGuid) throws FileUploadException, IOException, FileStorageException, SLException { ServletFileUpload upload = getFileUploadServlet(); long maxUploadSize = getConfiguration().getMaxUploadSize(); upload.setSizeMax(maxUploadSize); List<FileEntry> uploadedFiles = new ArrayList<FileEntry>(); FileItemIterator fileItemIterator = null; try { fileItemIterator = upload.getItemIterator(request); } catch (SizeLimitExceededException ex) { throw new SLException(MessageFormat.format(Messages.MAX_UPLOAD_SIZE_EXCEEDED, maxUploadSize)); } while (fileItemIterator.hasNext()) { FileItemStream item = fileItemIterator.next(); if (item.isFormField()) { continue; // ignore simple (non-file) form fields } InputStream in = null; try { in = item.openStream(); FileEntry entry = getFileService().addFile(spaceGuid, item.getName(), getConfiguration().getFileUploadProcessor(), in); uploadedFiles.add(entry); } finally { IOUtils.closeQuietly(in); } } return uploadedFiles; }
private InputStream getRequestStream(HttpServletRequest req, String expectedFieldName) throws Exception { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iterator = upload.getItemIterator(req); while (iterator.hasNext()) { FileItemStream item = iterator.next(); // LOG.info(item.getContentType()); if (item.getFieldName().equals(expectedFieldName)) { return item.openStream(); } } throw new IllegalArgumentException("Field " + expectedFieldName + " not found in upload"); }
private InputStream getRequestStream(HttpServletRequest req, String expectedFieldName) throws Exception { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iterator = upload.getItemIterator(req); while (iterator.hasNext()) { FileItemStream item = iterator.next(); if (item.getFieldName().equals(expectedFieldName)) { return item.openStream(); } } throw new IllegalArgumentException("Field " + expectedFieldName + " not found in upload"); }
public static String getFileType(FileItemStream file) { if (file != null) { String fileName = file.getName().toLowerCase(); String[] splitName = fileName.split("\\.", -1); String lastSplit = "." + splitName[splitName.length - 1]; return lastSplit; } return null; }
public static byte[] fileItemStreamToByteArray(FileItemStream item, int docType) throws IOException, FileUploadException { if (item != null && docType > 0) { byte[] array = IOUtils.toByteArray(item.openStream()); String[] types = new String[0]; boolean returnVal = false; if (docType == 1) { types = new String[]{".jpg", ".jpeg", ".png"}; } else if (docType == 2) { types = new String[]{".pdf", ".doc", ".docx"}; } else if (docType == 3) { types = new String[]{".pdf", ".jpg", ".jpeg", ".png"}; } for (String type : types) { if (getFileType(item).contains(type)) { returnVal = true; } } if (item.getName() != null && returnVal) { return array; } } throw new InvalidFormatException(); }
/** * * @param req * @return * @throws IOException */ private static Map<String, String[]> parseMultipartParameters(HttpServletRequest req) throws IOException { if (isMultipartContent(req)) { Map<String, String[]> multipartParameters = new HashMap(); Map<String, List<String>> map = new HashMap(); try { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(req); req.setAttribute(REQ_ATT_MULTIPART_ITERATOR, iter); while (iter.hasNext()) { FileItemStream item = iter.next(); if (!item.isFormField()) { req.setAttribute(REQ_ATT_MULTIPART_CURRENT_ITEM, item); break; } List<String> list = map.get(item.getFieldName()); if (list == null) { list = new ArrayList(); map.put(item.getFieldName(), list); } String encoding = req.getCharacterEncoding(); if (encoding == null) { encoding = "UTF-8"; } list.add(Miscellaneous.toString(item.openStream(), encoding)); } } catch (FileUploadException ex) { throw new RuntimeException(ex); } for (Map.Entry<String, List<String>> entrySet : map.entrySet()) { String key = entrySet.getKey(); List<String> value = entrySet.getValue(); multipartParameters.put(key, value.toArray(new String[value.size()])); } return multipartParameters; } return null; }
/** * Streams the file upload stream to the specified file. * * @param itemStream file item stream * @param file the file * @return true if stream was successfully * @throws IOException in case of IO errors */ private boolean streamFileToDisk(FileItemStream itemStream, File file) throws IOException { boolean result = false; try (InputStream input = itemStream.openStream(); OutputStream output = new BufferedOutputStream(new FileOutputStream(file), bufferSize)) { byte[] buffer = new byte[bufferSize]; LOG.debug("Streaming file using buffer size {}.", bufferSize); for (int length = 0; ((length = input.read(buffer)) > 0); ) { output.write(buffer, 0, length); } result = true; } return result; }
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; }
@Test public void blockingIOAdapterFunctionalTest() throws Exception { log.info("BLOCKING IO ADAPTER FUNCTIONAL TEST [ " + testCase.getDescription() + " ]"); if (log.isDebugEnabled()){ log.debug("Request body\n" + IOUtils.toString(testCase.getBodyInputStream())); } final FileUpload fileUpload = new FileUpload(); final FileItemIterator fileItemIterator = fileUpload.getItemIterator(testCase.getRequestContext()); try(final CloseableIterator<ParserToken> parts = Multipart.multipart(testCase.getMultipartContext()).forBlockingIO(testCase.getBodyInputStream())) { while (parts.hasNext()) { ParserToken parserToken = parts.next(); ParserToken.Type partItemType = parserToken.getType(); if (ParserToken.Type.NESTED_END.equals(partItemType) || ParserToken.Type.NESTED_START.equals(partItemType)) { // Commons file upload is not returning an item representing the start/end of a nested multipart. continue; } assertTrue(fileItemIterator.hasNext()); FileItemStream fileItemStream = fileItemIterator.next(); assertEquals(parserToken, fileItemStream); } } }
static void assertEquals(final ParserToken parserToken, final FileItemStream fileItemStream) throws IOException { if (parserToken instanceof BlockingIOAdapter.Part){ BlockingIOAdapter.Part part = (BlockingIOAdapter.Part) parserToken; assertHeadersAreEqual(fileItemStream.getHeaders(), part.getHeaders()); assertInputStreamsAreEqual(part.getPartBody(), fileItemStream.openStream()); }else{ fail("Invalid part item type " + parserToken.getClass()); } }
/** * Reads form values from the multipart request until a file is encountered. Field values are stored as strings for * retrieval using {@link #getFormFieldValue}. * @return True if there is an upload file available to read via {@link #getUploadFileItem()}. */ public boolean readFormData() { mUploadFileItem = null; try { while (mItemIterator.hasNext()) { FileItemStream lCurrentItem = mItemIterator.next(); /** * NOTE: the InputStream here is read here in a blocking way. Long upload hangs have been observed on live * environments at this point due to network issues. It should be possible to convert the stream to a * non-blocking stream at this point if required. */ InputStream lItemInputStream = lCurrentItem.openStream(); if (lCurrentItem.isFormField()) { //Read form values into the map String lParamName = lCurrentItem.getFieldName(); String lFieldValue = Streams.asString(lItemInputStream); mFieldParamMap.put(lParamName, lFieldValue); } else { //We've hit the file field, so stop the read for now mUploadFileItem = lCurrentItem; break; } lItemInputStream.close(); } } catch (IOException | FileUploadException e) { throw new ExInternal("Failed to read form data for the multipart request", e); } return mUploadFileItem != null; }
private void initialiseUpload() throws Throwable { try { FileItemStream lCurrentItem = mMultipartUploadReader.getUploadFileItem(); if(lCurrentItem == null) { throw new ExInternal("No file available on the multipart upload reader - either reader is in an invalid state, or the upload contained no file field"); } mItemInputStream = lCurrentItem.openStream(); if (lCurrentItem.isFormField()) { //Skip form fields, they should have been read by the MultipartUploadReader Track.alert("UploadWorkItem", "Unexpected form field encountered when streaming upload"); } else { mItemNonBlockingInputStream = new NonBlockingInputStream(mItemInputStream, BYTE_READ_QUANTITY, MAX_SUBSEQUENT_BUFFER_READS); String lFilename = lCurrentItem.getName(); mUploadInfo.setOriginalFileLocation(lFilename); int lBeginningIndex = lFilename.lastIndexOf("\\"); if ( lFilename != null && lBeginningIndex != -1 ) { // substr from that last occurrence of a back slash lFilename = lFilename.substring(lBeginningIndex + 1); } mUploadInfo.setFilename(lFilename); String lContentType = lCurrentItem.getContentType(); mUploadInfo.setBrowserContentType(lContentType != null ? lContentType : "" ); mStatus = READING_FILE_DATA; mLastReadTime = System.currentTimeMillis(); } } catch (Throwable ex1) { throw ex1; } }