List of usage examples for org.apache.commons.fileupload FileItemStream isFormField
boolean isFormField();
FileItem
instance represents a simple form field. From source file:ai.ilikeplaces.servlets.GenericFileGrabber.java
private Return<File> processFileUploadRequest(final FileItemIterator iter, final HttpSession session) throws IOException, FileUploadException { String returnVal = "Sorry! No Items To Process"; final Map<String, String> parameterMap = new HashMap<String, String>(); final File tempFile = getTempFile(); String userFileExtension = null; while (iter.hasNext()) { final FileItemStream item = iter.next(); final String paramName = item.getFieldName(); final InputStream stream = item.openStream(); if (item.isFormField()) {//Parameter-Value final String paramValue = Streams.asString(stream); parameterMap.put(paramName, paramValue); }/*from w w w.j a v a 2 s. co m*/ if (!item.isFormField()) { final String usersFileName = item.getName(); final int extensionDotIndex = usersFileName.lastIndexOf("."); userFileExtension = usersFileName.substring(extensionDotIndex + 1); final FileOutputStream fos = new FileOutputStream(tempFile); int byteCount = 0; while (true) { final int dataByte = stream.read(); if (byteCount++ > UPLOAD_LIMIT) { fos.close(); tempFile.delete(); return new ReturnImpl<File>(ExceptionCache.FILE_SIZE_EXCEPTION, "File Too Big!", true); } if (dataByte != -1) { fos.write(dataByte); } else { break;//break loop } } fos.close(); } } final FileUploadListenerFace<File> fulf; /** * Implement this as a set of listeners. Why it wasn't done now is that, a new object of listener should be * created per request and added to the listener pool(list or array whatever). */ switch (Integer.parseInt(parameterMap.get("type"))) { case 1: fulf = CDNProfilePhoto.getProfilePhotoCDNLocal(); break; case 2: fulf = CDNAlbumPrivateEvent.getAlbumPhotoCDNLocal(); break; case 3: fulf = CDNAlbumTribe.getAlbumTribeCDNLocal(); break; default: return new ReturnImpl<File>(ExceptionCache.UNSUPPORTED_SWITCH, "Unsupported Case", true); } if (tempFile == null) { return new ReturnImpl<File>(ExceptionCache.UNSUPPORTED_OPERATION_EXCEPTION, "No File!", true); } return fulf.run(tempFile, parameterMap, userFileExtension, session); }
From source file:de.kp.ames.web.function.upload.UploadServiceImpl.java
public void doSetRequest(RequestContext ctx) { /*/*from w w w . jav a 2 s . com*/ * The result of the upload request, returned * to the requestor; note, that the result must * be a text response */ boolean result = false; HttpServletRequest request = ctx.getRequest(); try { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { /* * Create new file upload handler */ ServletFileUpload upload = new ServletFileUpload(); /* * Parse the request */ FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream fileItem = iter.next(); if (fileItem.isFormField()) { // not supported } else { /* * Hook into the upload request to some virus scanning * using the scanner factory of this application */ byte[] bytes = FileUtil.getByteArrayFromInputStream(fileItem.openStream()); boolean checked = MalwareScanner.scanForViruses(bytes); if (checked) { String item = this.method.getAttribute(MethodConstants.ATTR_ITEM); String type = this.method.getAttribute(MethodConstants.ATTR_TYPE); if ((item == null) || (type == null)) { this.sendNotImplemented(ctx); } else { String fileName = FilenameUtils.getName(fileItem.getName()); String mimeType = fileItem.getContentType(); try { result = upload(item, type, fileName, mimeType, bytes); } catch (Exception e) { sendBadRequest(ctx, e); } } } } } } /* * Send html response */ if (result == true) { this.sendHTMLResponse(createHtmlSuccess(), ctx.getResponse()); } else { this.sendHTMLResponse(createHtmlFailure(), ctx.getResponse()); } } catch (Exception e) { this.sendBadRequest(ctx, e); } finally { } }
From source file:com.webpagebytes.cms.controllers.FileController.java
public void uploadFolder(HttpServletRequest request, HttpServletResponse response, String requestUri) throws WPBException { try {// ww w.j ava2s . co m ServletFileUpload upload = new ServletFileUpload(); upload.setHeaderEncoding("UTF-8"); FileItemIterator iterator = upload.getItemIterator(request); WPBFile ownerFile = null; Map<String, WPBFile> subfolderFiles = new HashMap<String, WPBFile>(); while (iterator.hasNext()) { FileItemStream item = iterator.next(); if (item.isFormField() && item.getFieldName().equals("ownerExtKey")) { String ownerExtKey = Streams.asString(item.openStream()); ownerFile = getDirectory(ownerExtKey, adminStorage); } else if (!item.isFormField() && item.getFieldName().equals("file")) { String fullName = item.getName(); String directoryPath = getDirectoryFromLongName(fullName); String fileName = getFileNameFromLongName(fullName); Map<String, WPBFile> tempSubFolders = checkAndCreateSubDirectory(directoryPath, ownerFile); subfolderFiles.putAll(tempSubFolders); // delete the existing file WPBFile existingFile = getFileFromDirectory(subfolderFiles.get(directoryPath), fileName); if (existingFile != null) { deleteFile(existingFile, 0); } // create the file WPBFile file = new WPBFile(); file.setExternalKey(adminStorage.getUniqueId()); file.setFileName(fileName); file.setLastModified(Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTime()); file.setDirectoryFlag(0); addFileToDirectory(subfolderFiles.get(directoryPath), file, item.openStream()); } } org.json.JSONObject returnJson = new org.json.JSONObject(); returnJson.put(DATA, jsonObjectConverter.JSONFromObject(null)); httpServletToolbox.writeBodyResponseAsJson(response, returnJson, null); } catch (Exception e) { Map<String, String> errors = new HashMap<String, String>(); errors.put("", WPBErrors.WB_CANT_UPDATE_RECORD); httpServletToolbox.writeBodyResponseAsJson(response, jsonObjectConverter.JSONObjectFromMap(null), errors); } }
From source file:com.webpagebytes.cms.controllers.FileController.java
public void upload(HttpServletRequest request, HttpServletResponse response, String requestUri) throws WPBException { try {/* w w w . j av a2 s . com*/ ServletFileUpload upload = new ServletFileUpload(); upload.setHeaderEncoding("UTF-8"); FileItemIterator iterator = upload.getItemIterator(request); WPBFile ownerFile = null; while (iterator.hasNext()) { FileItemStream item = iterator.next(); if (item.isFormField() && item.getFieldName().equals("ownerExtKey")) { String ownerExtKey = Streams.asString(item.openStream()); ownerFile = getDirectory(ownerExtKey, adminStorage); } else if (!item.isFormField() && item.getFieldName().equals("file")) { InputStream stream = item.openStream(); WPBFile wbFile = null; String fileName = getFileNameFromLongName(item.getName()); if (request.getAttribute("key") != null) { // this is an upload as update for an existing file Long key = Long.valueOf((String) request.getAttribute("key")); wbFile = adminStorage.get(key, WPBFile.class); ownerFile = getDirectory(wbFile.getOwnerExtKey(), adminStorage); //old file need to be deleted from cloud String oldFilePath = wbFile.getBlobKey(); if (oldFilePath != null && oldFilePath.length() > 0) { // delete only if the blob key is set WPBFilePath oldCloudFile = new WPBFilePath(PUBLIC_BUCKET, oldFilePath); cloudFileStorage.deleteFile(oldCloudFile); } } else { // this is a new upload wbFile = new WPBFile(); wbFile.setExternalKey(adminStorage.getUniqueId()); } wbFile.setFileName(fileName); wbFile.setLastModified(Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTime()); wbFile.setDirectoryFlag(0); addFileToDirectory(ownerFile, wbFile, stream); } } org.json.JSONObject returnJson = new org.json.JSONObject(); returnJson.put(DATA, jsonObjectConverter.JSONFromObject(null)); httpServletToolbox.writeBodyResponseAsJson(response, returnJson, null); } catch (Exception e) { Map<String, String> errors = new HashMap<String, String>(); errors.put("", WPBErrors.WB_CANT_UPDATE_RECORD); httpServletToolbox.writeBodyResponseAsJson(response, jsonObjectConverter.JSONObjectFromMap(null), errors); } }
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();/*w w w . java2 s . 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 w w w . j a va2s . 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(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:controllers.UploadController.java
/** * /*from w w w. j av a 2 s .co m*/ * This upload method expects a file and simply displays the file in the * multipart upload again to the user (in the correct mime encoding). * * @param context * @return * @throws Exception */ public Result uploadFinish(Context context) throws Exception { // we are using a renderable inner class to stream the input again to // the user Renderable renderable = new Renderable() { @Override public void render(Context context, Result result) { try { // make sure the context really is a multipart context... if (context.isMultipart()) { // This is the iterator we can use to iterate over the // contents // of the request. FileItemIterator fileItemIterator = context.getFileItemIterator(); while (fileItemIterator.hasNext()) { FileItemStream item = fileItemIterator.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); String contentType = item.getContentType(); if (contentType != null) { result.contentType(contentType); } else { contentType = mimeTypes.getMimeType(name); } ResponseStreams responseStreams = context.finalizeHeaders(result); 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 ByteStreams.copy(stream, responseStreams.getOutputStream()); } } } } catch (IOException | FileUploadException exception) { throw new InternalServerErrorException(exception); } } }; return new Result(200).render(renderable); }
From source file:com.zimbra.cs.service.UserServletContext.java
public InputStream getRequestInputStream(long limit) throws IOException, ServiceException, UserServletException { String contentType = MimeConstants.CT_APPLICATION_OCTET_STREAM; String filename = null;/* w w w. ja va 2 s. c om*/ InputStream is = null; final long DEFAULT_MAX_SIZE = 10 * 1024 * 1024; if (limit == 0) { if (req.getParameter("lbfums") != null) { limit = Provisioning.getInstance().getLocalServer() .getLongAttr(Provisioning.A_zimbraFileUploadMaxSize, DEFAULT_MAX_SIZE); } else { limit = Provisioning.getInstance().getConfig().getLongAttr(Provisioning.A_zimbraMtaMaxMessageSize, DEFAULT_MAX_SIZE); } } boolean doCsrfCheck = false; if (req.getAttribute(CsrfFilter.CSRF_TOKEN_CHECK) != null) { doCsrfCheck = (Boolean) req.getAttribute(CsrfFilter.CSRF_TOKEN_CHECK); } if (ServletFileUpload.isMultipartContent(req)) { ServletFileUpload sfu = new ServletFileUpload(); try { FileItemIterator iter = sfu.getItemIterator(req); while (iter.hasNext()) { FileItemStream fis = iter.next(); if (fis.isFormField()) { is = fis.openStream(); params.put(fis.getFieldName(), new String(ByteUtil.getContent(is, -1), "UTF-8")); if (doCsrfCheck && !this.csrfAuthSucceeded) { String csrfToken = params.get(FileUploadServlet.PARAM_CSRF_TOKEN); if (UserServlet.log.isDebugEnabled()) { String paramValue = req.getParameter(UserServlet.QP_AUTH); UserServlet.log.debug( "CSRF check is: %s, CSRF token is: %s, Authentication recd with request is: %s", doCsrfCheck, csrfToken, paramValue); } if (!CsrfUtil.isValidCsrfToken(csrfToken, authToken)) { setCsrfAuthSucceeded(Boolean.FALSE); UserServlet.log.debug( "CSRF token validation failed for account: %s" + ", Auth token is CSRF enabled: %s" + "CSRF token is: %s", authToken, authToken.isCsrfTokenEnabled(), csrfToken); throw new UserServletException(HttpServletResponse.SC_UNAUTHORIZED, L10nUtil.getMessage(MsgKey.errMustAuthenticate)); } else { setCsrfAuthSucceeded(Boolean.TRUE); } } is.close(); is = null; } else { is = new UploadInputStream(fis.openStream(), limit); break; } } } catch (UserServletException e) { throw new UserServletException(e.getHttpStatusCode(), e.getMessage(), e); } catch (Exception e) { throw new UserServletException(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, e.toString()); } if (is == null) throw new UserServletException(HttpServletResponse.SC_NO_CONTENT, "No file content"); } else { ContentType ctype = new ContentType(req.getContentType()); String contentEncoding = req.getHeader("Content-Encoding"); contentType = ctype.getContentType(); filename = ctype.getParameter("name"); if (filename == null || filename.trim().equals("")) filename = new ContentDisposition(req.getHeader("Content-Disposition")).getParameter("filename"); is = new UploadInputStream(contentEncoding != null && contentEncoding.indexOf("gzip") != -1 ? new GZIPInputStream(req.getInputStream()) : req.getInputStream(), limit); } if (filename == null || filename.trim().equals("")) filename = "unknown"; else params.put(UserServlet.UPLOAD_NAME, filename); params.put(UserServlet.UPLOAD_TYPE, contentType); ZimbraLog.mailbox.info("UserServlet received file %s - %d request bytes", filename, req.getContentLength()); return is; }
From source file:fi.iki.elonen.SimpleWebServer.java
private Response getUploadMsgAndExec(IHTTPSession session) throws FileUploadException, IOException { uploader = new NanoFileUpload(new DiskFileItemFactory()); files = new HashMap<String, List<FileItem>>(); FileItemIterator iter = uploader.getItemIterator(session); String fileName = "", newFileName = ""; try {//from w w w. j av a 2s . co m while (iter.hasNext()) { FileItemStream item = iter.next(); fileName = item.getName(); newFileName = rootDirs.get(0) + "/".concat(fileName); FileItem fileItem = uploader.getFileItemFactory().createItem(item.getFieldName(), item.getContentType(), item.isFormField(), newFileName); files.put(fileItem.getFieldName(), Arrays.asList(new FileItem[] { fileItem })); try { Streams.copy(item.openStream(), (new FileOutputStream(newFileName)), true); } catch (Exception e) { System.err.println(e.getMessage()); } fileItem.setHeaders(item.getHeaders()); } } catch (FileUploadException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return newFixedLengthResponse( "<html><body> \n File: " + fileName + " upload to " + newFileName + "! \n </body></html>\n"); }
From source file:com.google.sampling.experiential.server.EventServlet.java
private void processCsvUpload(HttpServletRequest req, HttpServletResponse resp) { PrintWriter out = null;/* ww w.j a v a 2s . co m*/ try { out = resp.getWriter(); } catch (IOException e1) { log.log(Level.SEVERE, "Cannot get an output PrintWriter!"); } try { boolean isDevInstance = isDevInstance(req); ServletFileUpload fileUploadTool = new ServletFileUpload(); fileUploadTool.setSizeMax(50000); resp.setContentType("text/html;charset=UTF-8"); FileItemIterator iterator = fileUploadTool.getItemIterator(req); while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream in = null; try { in = item.openStream(); if (item.isFormField()) { out.println("Got a form field: " + item.getFieldName()); } else { String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); out.println("--------------"); out.println("fileName = " + fileName); out.println("field name = " + fieldName); out.println("contentType = " + contentType); String fileContents = null; fileContents = IOUtils.toString(in); out.println("length: " + fileContents.length()); out.println(fileContents); saveCSV(fileContents, isDevInstance); } } catch (ParseException e) { log.info("Parse Exception: " + e.getMessage()); out.println("Could not parse your csv upload: " + e.getMessage()); } finally { in.close(); } } } catch (SizeLimitExceededException e) { log.info("SizeLimitExceededException: " + e.getMessage()); out.println("You exceeded the maximum size (" + e.getPermittedSize() + ") of the file (" + e.getActualSize() + ")"); return; } catch (IOException e) { log.severe("IOException: " + e.getMessage()); out.println("Error in receiving file."); } catch (FileUploadException e) { log.severe("FileUploadException: " + e.getMessage()); out.println("Error in receiving file."); } }