List of usage examples for org.apache.commons.fileupload FileItemStream getContentType
String getContentType();
null
if not defined. From source file:lucee.runtime.type.scope.FormImpl.java
private void initializeMultiPart(PageContext pc, boolean scriptProteced) { // get temp directory Resource tempDir = ((ConfigImpl) pc.getConfig()).getTempDirectory(); Resource tempFile;/*from ww w . java2 s. c om*/ // Create a new file upload handler final String encoding = getEncoding(); FileItemFactory factory = tempDir instanceof File ? new DiskFileItemFactory(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD, (File) tempDir) : new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding(encoding); //ServletRequestContext c = new ServletRequestContext(pc.getHttpServletRequest()); HttpServletRequest req = pc.getHttpServletRequest(); ServletRequestContext context = new ServletRequestContext(req) { public String getCharacterEncoding() { return encoding; } }; // Parse the request try { FileItemIterator iter = upload.getItemIterator(context); //byte[] value; InputStream is; ArrayList<URLItem> list = new ArrayList<URLItem>(); while (iter.hasNext()) { FileItemStream item = iter.next(); is = IOUtil.toBufferedInputStream(item.openStream()); if (item.getContentType() == null || StringUtil.isEmpty(item.getName())) { list.add(new URLItem(item.getFieldName(), new String(IOUtil.toBytes(is), encoding), false)); } else { tempFile = tempDir.getRealResource(getFileName()); fileItems.put(item.getFieldName().toLowerCase(), new Item(tempFile, item.getContentType(), item.getName(), item.getFieldName())); String value = tempFile.toString(); IOUtil.copy(is, tempFile, true); list.add(new URLItem(item.getFieldName(), value, false)); } } raw = list.toArray(new URLItem[list.size()]); fillDecoded(raw, encoding, scriptProteced, pc.getApplicationContext().getSameFieldAsArray(SCOPE_FORM)); } catch (Exception e) { //throw new PageRuntimeException(Caster.toPageException(e)); fillDecodedEL(new URLItem[0], encoding, scriptProteced, pc.getApplicationContext().getSameFieldAsArray(SCOPE_FORM)); initException = e; } }
From source file:com.pronoiahealth.olhie.server.rest.BooklogoUploadServiceImpl.java
@Override @POST// w w w .j av a 2 s .c om @Path("/upload") @Produces("text/html") @SecureAccess({ SecurityRoleEnum.ADMIN, SecurityRoleEnum.AUTHOR }) public String process(@Context HttpServletRequest req) throws ServletException, IOException, FileUploadException { try { // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(req); if (isMultipart == true) { // FileItemFactory fileItemFactory = new FileItemFactory(); String bookId = null; String contentType = null; // String data = null; byte[] bytes = null; String fileName = null; long size = 0; ServletFileUpload fileUpload = new ServletFileUpload(); fileUpload.setSizeMax(FILE_SIZE_LIMIT); FileItemIterator iter = fileUpload.getItemIterator(req); while (iter.hasNext()) { FileItemStream item = iter.next(); InputStream stream = item.openStream(); if (item.isFormField()) { // BookId if (item.getFieldName().equals("bookId")) { bookId = Streams.asString(stream); } } else { if (item != null) { contentType = item.getContentType(); fileName = item.getName(); item.openStream(); InputStream in = item.openStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(in, bos); bytes = bos.toByteArray(); // fileItem.get(); size = bytes.length; // data = Base64.encodeBytes(bytes); } } } // Add the logo Book book = bookDAO.getBookById(bookId); // Update the front cover BookCategory cat = holder.getCategoryByName(book.getCategory()); BookCover cover = holder.getCoverByName(book.getCoverName()); String authorName = bookDAO.getAuthorName(book.getAuthorId()); //String frontBookCoverEncoded = imgService // .createDefaultFrontCoverEncoded(book, cat, cover, // bytes, authorName); byte[] frontBookCoverBytes = imgService.createDefaultFrontCover(book, cat, cover, bytes, authorName); //String smallFrontBookCoverEncoded = imgService // .createDefaultSmallFrontCoverEncoded(book, cat, cover, // bytes, authorName); byte[] frontBookCoverSmallBytes = imgService.createDefaultSmallFrontCover(book, cat, cover, bytes, authorName); // Save it // Add the logo book = bookDAO.addLogoAndFrontCoverBytes(bookId, contentType, bytes, fileName, size, frontBookCoverBytes, frontBookCoverSmallBytes); } return "OK"; } catch (Exception e) { log.log(Level.SEVERE, "Throwing servlet exception for unhandled exception", e); // return "ERROR:\n" + e.getMessage(); if (e instanceof FileUploadException) { throw (FileUploadException) e; } else { throw new FileUploadException(e.getMessage()); } } }
From source file:com.liferay.faces.metal.component.inputfile.internal.InputFileDecoderCommonsImpl.java
@Override public Map<String, List<UploadedFile>> decode(FacesContext facesContext, String location) { Map<String, List<UploadedFile>> uploadedFileMap = null; ExternalContext externalContext = facesContext.getExternalContext(); String uploadedFilesFolder = getUploadedFilesFolder(externalContext, location); // Using the sessionId, determine a unique folder path and create the path if it does not exist. String sessionId = getSessionId(externalContext); // FACES-1452: Non-alpha-numeric characters must be removed order to ensure that the folder will be // created properly. sessionId = sessionId.replaceAll("[^A-Za-z0-9]", " "); File uploadedFilesPath = new File(uploadedFilesFolder, sessionId); if (!uploadedFilesPath.exists()) { uploadedFilesPath.mkdirs();/*from ww w .ja v a 2s . c o m*/ } // Initialize commons-fileupload with the file upload path. DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setRepository(uploadedFilesPath); // Initialize commons-fileupload so that uploaded temporary files are not automatically deleted. diskFileItemFactory.setFileCleaningTracker(null); // Initialize the commons-fileupload size threshold to zero, so that all files will be dumped to disk // instead of staying in memory. diskFileItemFactory.setSizeThreshold(0); // Determine the max file upload size threshold (in bytes). int uploadedFileMaxSize = WebConfigParam.UploadedFileMaxSize.getIntegerValue(externalContext); // Parse the request parameters and save all uploaded files in a map. ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); servletFileUpload.setFileSizeMax(uploadedFileMaxSize); uploadedFileMap = new HashMap<String, List<UploadedFile>>(); UploadedFileFactory uploadedFileFactory = (UploadedFileFactory) FactoryExtensionFinder .getFactory(UploadedFileFactory.class); // Begin parsing the request for file parts: try { FileItemIterator fileItemIterator = null; HttpServletRequest httpServletRequest = (HttpServletRequest) externalContext.getRequest(); fileItemIterator = servletFileUpload.getItemIterator(httpServletRequest); if (fileItemIterator != null) { int totalFiles = 0; // For each field found in the request: while (fileItemIterator.hasNext()) { try { totalFiles++; // Get the stream of field data from the request. FileItemStream fieldStream = (FileItemStream) fileItemIterator.next(); // Get field name from the field stream. String fieldName = fieldStream.getFieldName(); // Get the content-type, and file-name from the field stream. String contentType = fieldStream.getContentType(); boolean formField = fieldStream.isFormField(); String fileName = null; try { fileName = fieldStream.getName(); } catch (InvalidFileNameException e) { fileName = e.getName(); } // Copy the stream of file data to a temporary file. NOTE: This is necessary even if the // current field is a simple form-field because the call below to diskFileItem.getString() // will fail otherwise. DiskFileItem diskFileItem = (DiskFileItem) diskFileItemFactory.createItem(fieldName, contentType, formField, fileName); Streams.copy(fieldStream.openStream(), diskFileItem.getOutputStream(), true); // If the current field is a file, then if (!diskFileItem.isFormField()) { // Get the location of the temporary file that was copied from the request. File tempFile = diskFileItem.getStoreLocation(); // If the copy was successful, then if (tempFile.exists()) { // Copy the commons-fileupload temporary file to a file in the same temporary // location, but with the filename provided by the user in the upload. This has two // benefits: 1) The temporary file will have a nice meaningful name. 2) By copying // the file, the developer can have access to a semi-permanent file, because the // commmons-fileupload DiskFileItem.finalize() method automatically deletes the // temporary one. String tempFileName = tempFile.getName(); String tempFileAbsolutePath = tempFile.getAbsolutePath(); String copiedFileName = stripIllegalCharacters(fileName); String copiedFileAbsolutePath = tempFileAbsolutePath.replace(tempFileName, copiedFileName); File copiedFile = new File(copiedFileAbsolutePath); FileUtils.copyFile(tempFile, copiedFile); // If present, build up a map of headers. Map<String, List<String>> headersMap = new HashMap<String, List<String>>(); FileItemHeaders fileItemHeaders = fieldStream.getHeaders(); if (fileItemHeaders != null) { Iterator<String> headerNameItr = fileItemHeaders.getHeaderNames(); if (headerNameItr != null) { while (headerNameItr.hasNext()) { String headerName = headerNameItr.next(); Iterator<String> headerValuesItr = fileItemHeaders .getHeaders(headerName); List<String> headerValues = new ArrayList<String>(); if (headerValuesItr != null) { while (headerValuesItr.hasNext()) { String headerValue = headerValuesItr.next(); headerValues.add(headerValue); } } headersMap.put(headerName, headerValues); } } } // Put a valid UploadedFile instance into the map that contains all of the // uploaded file's attributes, along with a successful status. Map<String, Object> attributeMap = new HashMap<String, Object>(); String id = Long.toString(((long) hashCode()) + System.currentTimeMillis()); String message = null; UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile( copiedFileAbsolutePath, attributeMap, diskFileItem.getCharSet(), diskFileItem.getContentType(), headersMap, id, message, fileName, diskFileItem.getSize(), UploadedFile.Status.FILE_SAVED); addUploadedFile(uploadedFileMap, fieldName, uploadedFile); logger.debug("Received uploaded file fieldName=[{0}] fileName=[{1}]", fieldName, fileName); } else { if ((fileName != null) && (fileName.trim().length() > 0)) { Exception e = new IOException("Failed to copy the stream of uploaded file=[" + fileName + "] to a temporary file (possibly a zero-length uploaded file)"); UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e); addUploadedFile(uploadedFileMap, fieldName, uploadedFile); } } } } catch (Exception e) { logger.error(e); UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e); String fieldName = Integer.toString(totalFiles); addUploadedFile(uploadedFileMap, fieldName, uploadedFile); } } } } // If there was an error in parsing the request for file parts, then put a bogus UploadedFile instance in // the map so that the developer can have some idea that something went wrong. catch (Exception e) { logger.error(e); UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e); addUploadedFile(uploadedFileMap, "unknown", uploadedFile); } return uploadedFileMap; }
From source file:com.liferay.faces.alloy.component.inputfile.internal.InputFileDecoderCommonsImpl.java
@Override public Map<String, List<UploadedFile>> decode(FacesContext facesContext, String location) { Map<String, List<UploadedFile>> uploadedFileMap = null; ExternalContext externalContext = facesContext.getExternalContext(); String uploadedFilesFolder = getUploadedFilesFolder(externalContext, location); // Using the sessionId, determine a unique folder path and create the path if it does not exist. String sessionId = getSessionId(externalContext); // FACES-1452: Non-alpha-numeric characters must be removed order to ensure that the folder will be // created properly. sessionId = sessionId.replaceAll("[^A-Za-z0-9]", " "); File uploadedFilesPath = new File(uploadedFilesFolder, sessionId); if (!uploadedFilesPath.exists()) { uploadedFilesPath.mkdirs();/*from ww w . j ava 2s . c om*/ } // Initialize commons-fileupload with the file upload path. DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setRepository(uploadedFilesPath); // Initialize commons-fileupload so that uploaded temporary files are not automatically deleted. diskFileItemFactory.setFileCleaningTracker(null); // Initialize the commons-fileupload size threshold to zero, so that all files will be dumped to disk // instead of staying in memory. diskFileItemFactory.setSizeThreshold(0); // Determine the max file upload size threshold (in bytes). int uploadedFileMaxSize = WebConfigParam.UploadedFileMaxSize.getIntegerValue(externalContext); // Parse the request parameters and save all uploaded files in a map. ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); servletFileUpload.setFileSizeMax(uploadedFileMaxSize); uploadedFileMap = new HashMap<String, List<UploadedFile>>(); UploadedFileFactory uploadedFileFactory = (UploadedFileFactory) FactoryExtensionFinder .getFactory(externalContext, UploadedFileFactory.class); // Begin parsing the request for file parts: try { FileItemIterator fileItemIterator = null; HttpServletRequest httpServletRequest = (HttpServletRequest) externalContext.getRequest(); fileItemIterator = servletFileUpload.getItemIterator(httpServletRequest); if (fileItemIterator != null) { int totalFiles = 0; // For each field found in the request: while (fileItemIterator.hasNext()) { try { totalFiles++; // Get the stream of field data from the request. FileItemStream fieldStream = (FileItemStream) fileItemIterator.next(); // Get field name from the field stream. String fieldName = fieldStream.getFieldName(); // Get the content-type, and file-name from the field stream. String contentType = fieldStream.getContentType(); boolean formField = fieldStream.isFormField(); String fileName = null; try { fileName = fieldStream.getName(); } catch (InvalidFileNameException e) { fileName = e.getName(); } // Copy the stream of file data to a temporary file. NOTE: This is necessary even if the // current field is a simple form-field because the call below to diskFileItem.getString() // will fail otherwise. DiskFileItem diskFileItem = (DiskFileItem) diskFileItemFactory.createItem(fieldName, contentType, formField, fileName); Streams.copy(fieldStream.openStream(), diskFileItem.getOutputStream(), true); // If the current field is a file, then if (!diskFileItem.isFormField()) { // Get the location of the temporary file that was copied from the request. File tempFile = diskFileItem.getStoreLocation(); // If the copy was successful, then if (tempFile.exists()) { // Copy the commons-fileupload temporary file to a file in the same temporary // location, but with the filename provided by the user in the upload. This has two // benefits: 1) The temporary file will have a nice meaningful name. 2) By copying // the file, the developer can have access to a semi-permanent file, because the // commmons-fileupload DiskFileItem.finalize() method automatically deletes the // temporary one. String tempFileName = tempFile.getName(); String tempFileAbsolutePath = tempFile.getAbsolutePath(); String copiedFileName = stripIllegalCharacters(fileName); String copiedFileAbsolutePath = tempFileAbsolutePath.replace(tempFileName, copiedFileName); File copiedFile = new File(copiedFileAbsolutePath); FileUtils.copyFile(tempFile, copiedFile); // If present, build up a map of headers. Map<String, List<String>> headersMap = new HashMap<String, List<String>>(); FileItemHeaders fileItemHeaders = fieldStream.getHeaders(); if (fileItemHeaders != null) { Iterator<String> headerNameItr = fileItemHeaders.getHeaderNames(); if (headerNameItr != null) { while (headerNameItr.hasNext()) { String headerName = headerNameItr.next(); Iterator<String> headerValuesItr = fileItemHeaders .getHeaders(headerName); List<String> headerValues = new ArrayList<String>(); if (headerValuesItr != null) { while (headerValuesItr.hasNext()) { String headerValue = headerValuesItr.next(); headerValues.add(headerValue); } } headersMap.put(headerName, headerValues); } } } // Put a valid UploadedFile instance into the map that contains all of the // uploaded file's attributes, along with a successful status. Map<String, Object> attributeMap = new HashMap<String, Object>(); String id = Long.toString(((long) hashCode()) + System.currentTimeMillis()); String message = null; UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile( copiedFileAbsolutePath, attributeMap, diskFileItem.getCharSet(), diskFileItem.getContentType(), headersMap, id, message, fileName, diskFileItem.getSize(), UploadedFile.Status.FILE_SAVED); addUploadedFile(uploadedFileMap, fieldName, uploadedFile); logger.debug("Received uploaded file fieldName=[{0}] fileName=[{1}]", fieldName, fileName); } else { if ((fileName != null) && (fileName.trim().length() > 0)) { Exception e = new IOException("Failed to copy the stream of uploaded file=[" + fileName + "] to a temporary file (possibly a zero-length uploaded file)"); UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e); addUploadedFile(uploadedFileMap, fieldName, uploadedFile); } } } } catch (Exception e) { logger.error(e); UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e); String fieldName = Integer.toString(totalFiles); addUploadedFile(uploadedFileMap, fieldName, uploadedFile); } } } } // If there was an error in parsing the request for file parts, then put a bogus UploadedFile instance in // the map so that the developer can have some idea that something went wrong. catch (Exception e) { logger.error(e); UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e); addUploadedFile(uploadedFileMap, "unknown", uploadedFile); } return uploadedFileMap; }
From source file:etc.CloudStorage.java
/** * * This upload method expects a file and simply displays the file in the * multipart upload again to the user (in the correct mime encoding). * * * @return/*from w ww . j av a 2s . c om*/ * @throws Exception * @param context */ public Mp3 uploadMp3(Context context) throws Exception { // make sure the context really is a multipart context... Mp3 mp3 = null; if (context.isMultipart()) { // This is the iterator we can use to iterate over the contents of the request. try { FileItemIterator fileItemIterator = context.getFileItemIterator(); while (fileItemIterator.hasNext()) { FileItemStream item = fileItemIterator.next(); String name = item.getName(); // Store audio file GcsFilename filename = new GcsFilename("musaemachine.com", name); // Store generated waveform image GcsFilename waveImageFile = new GcsFilename("musaemachine.com", removeExtension(name).concat(".png")); InputStream stream = item.openStream(); String contentType = item.getContentType(); System.out.println("--- " + contentType); GcsFileOptions options = new GcsFileOptions.Builder().acl("public-read").mimeType(contentType) .build(); byte[] audioBuffer = getByteFromStream(stream); GcsOutputChannel outputChannel = gcsService.createOrReplace(filename, options); outputChannel.write(ByteBuffer.wrap(audioBuffer)); outputChannel.close(); // AudioWaveformCreator awc = new AudioWaveformCreator(); // byte[]waveform= awc.createWavForm(stream); // System.out.println("Buff Image---- "+waveform); // Saving waveform image // GcsOutputChannel waveFormOutputChannel = // gcsService.createOrReplace(waveImageFile, options); // waveFormOutputChannel.write(ByteBuffer.wrap(audioBuffer)); // waveFormOutputChannel.close(); // BodyContentHandler handler = new BodyContentHandler(); ParseContext pcontext = new ParseContext(); Metadata metadata = new Metadata(); mp3Parser.parse(stream, handler, metadata, pcontext); Double duration = Double.parseDouble(metadata.get("xmpDM:duration")); mp3 = new Mp3(name, duration); } } catch (Exception e) { e.printStackTrace(); } } return mp3; }
From source file:com.smartgwt.extensions.fileuploader.server.TestServiceImpl.java
private void processFiles(HttpServletRequest request, HttpServletResponse response) { HashMap<String, String> args = new HashMap<String, String>(); try {//from w w w . j av a 2 s . c o m ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(request); FileItemStream fileItem = null; // pick up parameters first and note actual FileItem while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); if (item.isFormField()) { args.put(name, Streams.asString(item.openStream())); } else { fileItem = item; } } if (fileItem != null) { args.put("contentType", fileItem.getContentType()); args.put("fileName", FileUtils.filename(fileItem.getName())); System.out.println("uploading args " + args); String context = args.get("context"); String model = args.get("model"); String xq = args.get("xq"); System.out.println(context + "," + model + "," + xq); File f = new File(args.get("fileName")); System.out.println(f.getAbsolutePath()); /* * TODO: pboysen get the state, context and fileManager and store the * stream in fileName. Parameters should be passed to locate state * and conversion options. */ response.setContentType("text/html"); response.setHeader("Pragma", "No-cache"); response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<script>"); out.println("top.uploadComplete('" + args.get("fileName") + "');"); out.println("</script>"); out.println("</body>"); out.println("</html>"); out.flush(); } else { //TODO: add error code } } catch (Exception e) { System.out.println(e.getMessage()); } }
From source file:com.threewks.thundr.bind.http.MultipartHttpBinder.java
void extractParameters(HttpServletRequest req, Map<String, List<String>> formFields, Map<String, MultipartFile> fileFields) { try {/*w w w . j av a 2s.c o m*/ FileItemIterator itemIterator = upload.getItemIterator(req); while (itemIterator.hasNext()) { FileItemStream item = itemIterator.next(); InputStream stream = item.openStream(); String fieldName = item.getFieldName(); if (item.isFormField()) { List<String> existing = formFields.get(fieldName); if (existing == null) { existing = new LinkedList<String>(); formFields.put(fieldName, existing); } existing.add(Streams.readString(stream)); } else { MultipartFile file = new MultipartFile(item.getName(), Streams.readBytes(stream), item.getContentType()); fileFields.put(fieldName, file); } stream.close(); } } catch (Exception e) { throw new BindException(e, "Failed to bind multipart form data: %s", e.getMessage()); } }
From source file:ca.nrc.cadc.beacon.web.resources.FileItemServerResourceTest.java
@Test public void uploadFileItem() throws Exception { final Map<String, Object> requestAttributes = new HashMap<>(); final VOSURI parentURI = new VOSURI(URI.create("vos://cadc.nrc.ca!vospace/parent/sub")); final VOSURI expectedURI = new VOSURI(URI.create("vos://cadc.nrc.ca!vospace/parent/sub/MYUPLOADFILE.txt")); final DataNode expectedDataNode = new DataNode(expectedURI); final String data = "MYUPLOADDATA"; final byte[] dataBytes = data.getBytes(); final InputStream inputStream = new ByteArrayInputStream(dataBytes); final List<NodeProperty> propertyList = new ArrayList<>(); propertyList.add(new NodeProperty("ivo://ivoa.net/vospace/core#length", "" + dataBytes.length)); propertyList.add(new NodeProperty("ivo://ivoa.net/vospace/core#MD5", new String(MessageDigest.getInstance("MD5").digest(dataBytes)))); expectedDataNode.setProperties(propertyList); requestAttributes.put("path", "my/file.txt"); expect(mockRequest.getEntity()).andReturn(new EmptyRepresentation()).once(); expect(mockServletContext.getContextPath()).andReturn("/teststorage").once(); replay(mockServletContext);//from w w w . ja va 2 s . co m testSubject = new FileItemServerResource(null, mockVOSpaceClient, new UploadVerifier(), new FileValidator()) { @Override public Response getResponse() { return mockResponse; } @Override ServletContext getServletContext() { return mockServletContext; } @Override public Request getRequest() { return mockRequest; } /** * Returns the request attributes. * * @return The request attributes. * @see Request#getAttributes() */ @Override public Map<String, Object> getRequestAttributes() { return requestAttributes; } @Override VOSURI getCurrentItemURI() { return parentURI; } /** * Abstract away the Transfer stuff. It's cumbersome. * * @param outputStreamWrapper The OutputStream wrapper. * @param dataNode The node to upload. * @throws Exception To capture transfer and upload failures. */ @Override void upload(UploadOutputStreamWrapper outputStreamWrapper, DataNode dataNode) throws Exception { // Do nothing. } @Override <T> T executeSecurely(PrivilegedExceptionAction<T> runnable) throws IOException { try { return runnable.run(); } catch (Exception e) { throw new RuntimeException(e); } } }; final FileItemStream mockFileItemStream = createMock(FileItemStream.class); expect(mockVOSpaceClient.getNode("/parent/sub/MYUPLOADFILE.txt")) .andThrow(new NodeNotFoundException("No such node.")).once(); expect(mockVOSpaceClient.createNode(expectedDataNode, false)).andReturn(expectedDataNode).once(); expect(mockFileItemStream.getName()).andReturn("MYUPLOADFILE.txt").once(); expect(mockFileItemStream.openStream()).andReturn(inputStream).once(); expect(mockFileItemStream.getContentType()).andReturn("text/plain").once(); replay(mockVOSpaceClient, mockResponse, mockRequest, mockFileItemStream); final VOSURI resultURI = testSubject.upload(mockFileItemStream); assertEquals("End URI is wrong.", expectedURI, resultURI); verify(mockVOSpaceClient, mockResponse, mockRequest, mockFileItemStream, mockServletContext); }
From source file:com.qualogy.qafe.web.UploadService.java
public String uploadFile(HttpServletRequest request) { ServletFileUpload upload = new ServletFileUpload(); String errorMessage = ""; byte[] filecontent = null; String appUUID = null;/* w w w . j av a 2 s. c o m*/ String windowId = null; String filename = null; String mimeType = null; InputStream inputStream = null; ByteArrayOutputStream outputStream = null; try { FileItemIterator fileItemIterator = upload.getItemIterator(request); while (fileItemIterator.hasNext()) { FileItemStream item = fileItemIterator.next(); inputStream = item.openStream(); // Read the file into a byte array. outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[8192]; int len = 0; while (-1 != (len = inputStream.read(buffer))) { outputStream.write(buffer, 0, len); } if (filecontent == null) { filecontent = outputStream.toByteArray(); filename = item.getName(); mimeType = item.getContentType(); } if (item.getFieldName().indexOf(APP_UUID) > -1) { appUUID = item.getFieldName() .substring(item.getFieldName().indexOf(APP_UUID) + APP_UUID.length() + 1); } if (item.getFieldName().indexOf(APP_WINDOWID) > -1) { windowId = item.getFieldName() .substring(item.getFieldName().indexOf(APP_WINDOWID) + APP_WINDOWID.length() + 1); } } if ((appUUID != null) && (windowId != null)) { if (filecontent != null) { int maxFileSize = 0; if (ApplicationCluster.getInstance() .getConfigurationItem(Configuration.MAX_UPLOAD_FILESIZE) != null) { String maxUploadFileSzie = ApplicationCluster.getInstance() .getConfigurationItem(Configuration.MAX_UPLOAD_FILESIZE); if (StringUtils.isNumeric(maxUploadFileSzie)) { maxFileSize = Integer.parseInt(maxUploadFileSzie); } } if ((maxFileSize == 0) || (filecontent.length <= maxFileSize)) { Map<String, Object> fileData = new HashMap<String, Object>(); fileData.put(FILE_MIME_TYPE, mimeType); fileData.put(FILE_NAME, filename); fileData.put(FILE_CONTENT, filecontent); String uploadUUID = DataStore.KEY_LOOKUP_DATA + UniqueIdentifier.nextSeed().toString(); appUUID = concat(appUUID, windowId); ApplicationLocalStore.getInstance().store(appUUID, uploadUUID, fileData); return filename + "#" + UPLOAD_COMPLETE + "=" + uploadUUID; } else { errorMessage = "The maxmimum filesize in bytes is " + maxFileSize; } } } else { errorMessage = "Application UUID not specified"; } inputStream.close(); outputStream.close(); } catch (Exception e) { errorMessage = e.getMessage(); } return UPLOAD_ERROR + "=" + "File can not be uploaded: " + errorMessage; }
From source file:com.northernwall.hadrian.handler.ImageHandler.java
private void updateImage(Request request, String serviceId) throws IOException, FileUploadException { if (!ServletFileUpload.isMultipartContent(request)) { logger.warn("Trying to upload image for {} but content is not multipart", serviceId); return;/*from w ww.jav a 2 s.c o m*/ } logger.info("Trying to upload image for {}", serviceId); ServletFileUpload upload = new ServletFileUpload(); // Parse the request FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); if (!item.isFormField()) { String name = item.getName(); name = name.replace(' ', '-').replace('&', '-').replace('<', '-').replace('>', '-') .replace('/', '-').replace('\\', '-').replace('&', '-').replace('@', '-').replace('?', '-') .replace('^', '-').replace('#', '-').replace('%', '-').replace('=', '-').replace('$', '-') .replace('{', '-').replace('}', '-').replace('[', '-').replace(']', '-').replace('|', '-') .replace(';', '-').replace(':', '-').replace('~', '-').replace('`', '-'); dataAccess.uploadImage(serviceId, name, item.getContentType(), item.openStream()); } } }