List of usage examples for org.apache.commons.fileupload FileItemStream getFieldName
String getFieldName();
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;// www . j a v a 2s.c o m // 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:ai.ilikeplaces.servlets.ServletFileUploads.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request__// w w w . ja v a 2 s . co m * @param response__ * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(final HttpServletRequest request__, final HttpServletResponse response__) throws ServletException, IOException { response__.setContentType("text/html;charset=UTF-8"); Loggers.DEBUG.debug(logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0020"), request__.getLocale()); PrintWriter out = response__.getWriter(); final ResourceBundle gUI = PropertyResourceBundle.getBundle("ai.ilikeplaces.rbs.GUI"); try { fileUpload: { if (!isFileUploadPermitted()) { errorTemporarilyDisabled(out); break fileUpload; } processSignOn: { final HttpSession session = request__.getSession(false); if (session == null) { errorNoLogin(out); break fileUpload; } else if (session.getAttribute(ServletLogin.HumanUser) == null) { errorNoLogin(out); break processSignOn; } processRequestType: { @SuppressWarnings("unchecked") final HumanUserLocal sBLoggedOnUserLocal = ((SessionBoundBadRefWrapper<HumanUserLocal>) session .getAttribute(ServletLogin.HumanUser)).getBoundInstance(); try { /*Check that we have a file upload request*/ final boolean isMultipart = ServletFileUpload.isMultipartContent(request__); if (!isMultipart) { LoggerFactory.getLogger(ServletFileUploads.class.getName()).error( logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0001")); errorNonMultipart(out); break processRequestType; } processRequest: { // Create a new file upload handler final ServletFileUpload upload = new ServletFileUpload(); // Parse the request FileItemIterator iter = upload.getItemIterator(request__); boolean persisted = false; loop: { Long locationId = null; String photoDescription = null; String photoName = null; Boolean isPublic = null; Boolean isPrivate = null; boolean fileSaved = false; while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); String absoluteFileSystemFileName = FilePath; InputStream stream = item.openStream(); @_fix(issue = "Handle no extension files") String usersFileName = null; String randomFileName = null; if (item.isFormField()) { final String value = Streams.asString(stream); Loggers.DEBUG.debug( logMsgs.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0002"), name); Loggers.DEBUG.debug( logMsgs.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0003"), value); if (name.equals("locationId")) { locationId = Long.parseLong(value); Loggers.DEBUG.debug((logMsgs.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0004"))); } if (name.equals("photoDescription")) { photoDescription = value; Loggers.DEBUG.debug((logMsgs.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0005"))); } if (name.equals("photoName")) { photoName = value; Loggers.DEBUG.debug((logMsgs.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0006"))); } if (name.equals("isPublic")) { if (!(value.equals("true") || value.equals("false"))) { throw new IllegalArgumentException(logMsgs.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0007") + value); } isPublic = Boolean.valueOf(value); Loggers.DEBUG.debug((logMsgs.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0008"))); } if (name.equals("isPrivate")) { if (!(value.equals("true") || value.equals("false"))) { throw new IllegalArgumentException(logMsgs.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0007") + value); } isPrivate = Boolean.valueOf(value); Loggers.DEBUG.debug("HELLO, I PROPERLY RECEIVED photoName."); } } if ((!item.isFormField())) { Loggers.DEBUG.debug((logMsgs.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0009") + name)); Loggers.DEBUG.debug((logMsgs .getString("ai.ilikeplaces.servlets.ServletFileUploads.0010") + item.getName())); // Process the input stream if (!(item.getName().lastIndexOf(".") > 0)) { errorFileType(out, item.getName()); break processRequest; } usersFileName = (item.getName().indexOf("\\") <= 1 ? item.getName() : item.getName() .substring(item.getName().lastIndexOf("\\") + 1)); final String userUploadedFileName = item.getName(); String fileExtension = "error"; if (userUploadedFileName.toLowerCase().endsWith(".jpg")) { fileExtension = ".jpg"; } else if (userUploadedFileName.toLowerCase().endsWith(".jpeg")) { fileExtension = ".jpeg"; } else if (userUploadedFileName.toLowerCase().endsWith(".png")) { fileExtension = ".png"; } else { errorFileType(out, gUI.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0019")); break processRequest; } randomFileName = getRandomFileName(locationId); randomFileName += fileExtension; final File uploadedFile = new File( absoluteFileSystemFileName += randomFileName); final FileOutputStream fos = new FileOutputStream(uploadedFile); while (true) { final int dataByte = stream.read(); if (dataByte != -1) { fos.write(dataByte); } else { break; } } fos.close(); stream.close(); fileSaved = true; } Loggers.DEBUG.debug( logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0011") + locationId); Loggers.DEBUG.debug( logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0012") + fileSaved); Loggers.DEBUG.debug( logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0013") + photoDescription); Loggers.DEBUG.debug( logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0014") + photoName); Loggers.DEBUG.debug( logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0015") + isPublic); if (fileSaved && (photoDescription != null)) { persistData: { handlePublicPrivateness: { if ((isPublic != null) && isPublic && (locationId != null)) { Return<PublicPhoto> r = DB .getHumanCRUDPublicPhotoLocal(true) .cPublicPhoto(sBLoggedOnUserLocal.getHumanUserId(), locationId, absoluteFileSystemFileName, photoName, photoDescription, new String(CDN + randomFileName), 4); if (r.returnStatus() == 0) { successFileName(out, usersFileName, logMsgs.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0016")); } else { errorBusy(out); } } else if ((isPrivate != null) && isPrivate) { Return<PrivatePhoto> r = DB .getHumanCRUDPrivatePhotoLocal(true) .cPrivatePhoto(sBLoggedOnUserLocal.getHumanUserId(), absoluteFileSystemFileName, photoName, photoDescription, new String(CDN + randomFileName)); if (r.returnStatus() == 0) { successFileName(out, usersFileName, "private"); } else { errorBusy(out); } } else { throw UNSUPPORTED_OPERATION_EXCEPTION; } } } /*We got what we need from the loop. Lets break it*/ break loop; } } } if (!persisted) { errorMissingParameters(out); break processRequest; } } } catch (FileUploadException ex) { Loggers.EXCEPTION.error(null, ex); errorBusy(out); } } } } } catch (final Throwable t_) { Loggers.EXCEPTION.error("SORRY! I ENCOUNTERED AN EXCEPTION DURING THE FILE UPLOAD", t_); } }
From source file:com.qualogy.qafe.web.upload.DatagridUploadServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { byte[] filecontent = null; ServletFileUpload upload = new ServletFileUpload(); InputStream inputStream = null; ByteArrayOutputStream outputStream = null; boolean isFirstLineHeader = false; String delimiter = ","; writeUploadInfo(request);//from w w w.java2s . co m log(request.getHeader("User-Agent")); response.setContentType("text/html"); PrintWriter out = response.getWriter(); 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(); } if (FORM_PARAMETER_DELIMITER.equals(item.getFieldName())) { delimiter = outputStream.toString(); } else if (FORM_PARAMETER_ISFIRSTLINEHEADER.equals(item.getFieldName())) { if ("on".equals(outputStream.toString())) { isFirstLineHeader = true; } } } inputStream.close(); outputStream.close(); } catch (FileUploadException e) { ExceptionHelper.printStackTrace(e); } catch (RuntimeException e) { out.print("Conversion failed. Please check the file. Message :" + e.getMessage()); } DocumentParameter dp = new DocumentParameter(); dp.setDelimiter(delimiter); dp.setFirstFieldHeader(isFirstLineHeader); dp.setData(filecontent); try { DocumentOutput dout = documentService.processExcelUpload(dp); String uploadUUID = DataStore.KEY_LOOKUP_DATA + dout.getUuid(); ApplicationLocalStore.getInstance().store(uploadUUID, uploadUUID, dout.getData()); out.print("UUID=" + uploadUUID); } catch (Exception e) { out.print("Conversion failed. Please check the file (" + e.getMessage() + ")"); } }
From source file:com.webpagebytes.cms.controllers.FileController.java
public void uploadFolder(HttpServletRequest request, HttpServletResponse response, String requestUri) throws WPBException { try {// www . j ava 2s. 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 {/*from w ww. java 2 s . c o m*/ 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:de.mpg.imeji.presentation.upload.UploadServlet.java
/** * Download the file on the disk in a tmp file * * @param req/* w w w . j ava 2 s . com*/ * @return * @throws FileUploadException * @throws IOException */ private UploadItem doUpload(HttpServletRequest req) { try { final ServletFileUpload upload = new ServletFileUpload(); final FileItemIterator iter = upload.getItemIterator(req); UploadItem uploadItem = new UploadItem(); while (iter.hasNext()) { final FileItemStream fis = iter.next(); if (!fis.isFormField()) { uploadItem.setFilename(fis.getName()); final File tmp = TempFileUtil.createTempFile("upload", null); StorageUtils.writeInOut(fis.openStream(), new FileOutputStream(tmp), true); uploadItem.setFile(tmp); } else { ByteArrayOutputStream out = new ByteArrayOutputStream(); StorageUtils.writeInOut(fis.openStream(), out, true); uploadItem.getParams().put(fis.getFieldName(), out.toString("UTF-8")); } } return uploadItem; } catch (final Exception e) { LOGGER.error("Error file upload", e); } return new UploadItem(); }
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;/*from w w w.jav a 2s . 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.liferay.faces.bridge.context.map.internal.MultiPartFormDataProcessorImpl.java
@Override public Map<String, List<UploadedFile>> process(ClientDataRequest clientDataRequest, PortletConfig portletConfig, FacesRequestParameterMap facesRequestParameterMap) { Map<String, List<UploadedFile>> uploadedFileMap = null; PortletSession portletSession = clientDataRequest.getPortletSession(); String uploadedFilesDir = PortletConfigParam.UploadedFilesDir.getStringValue(portletConfig); // Using the portlet sessionId, determine a unique folder path and create the path if it does not exist. String sessionId = portletSession.getId(); // 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]", StringPool.BLANK); File uploadedFilesPath = new File(uploadedFilesDir, sessionId); if (!uploadedFilesPath.exists()) { uploadedFilesPath.mkdirs();/* ww w . j a v a2 s. co 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). long uploadedFileMaxSize = PortletConfigParam.UploadedFileMaxSize.getLongValue(portletConfig); // Parse the request parameters and save all uploaded files in a map. PortletFileUpload portletFileUpload = new PortletFileUpload(diskFileItemFactory); portletFileUpload.setFileSizeMax(uploadedFileMaxSize); uploadedFileMap = new HashMap<String, List<UploadedFile>>(); // FACES-271: Include name+value pairs found in the ActionRequest. Set<Map.Entry<String, String[]>> actionRequestParameterSet = clientDataRequest.getParameterMap().entrySet(); for (Map.Entry<String, String[]> mapEntry : actionRequestParameterSet) { String parameterName = mapEntry.getKey(); String[] parameterValues = mapEntry.getValue(); if (parameterValues.length > 0) { for (String parameterValue : parameterValues) { facesRequestParameterMap.addValue(parameterName, parameterValue); } } } UploadedFileFactory uploadedFileFactory = (UploadedFileFactory) BridgeFactoryFinder .getFactory(UploadedFileFactory.class); // Begin parsing the request for file parts: try { FileItemIterator fileItemIterator = null; if (clientDataRequest instanceof ResourceRequest) { ResourceRequest resourceRequest = (ResourceRequest) clientDataRequest; fileItemIterator = portletFileUpload.getItemIterator(new ActionRequestAdapter(resourceRequest)); } else { ActionRequest actionRequest = (ActionRequest) clientDataRequest; fileItemIterator = portletFileUpload.getItemIterator(actionRequest); } if (fileItemIterator != null) { int totalFiles = 0; String namespace = facesRequestParameterMap.getNamespace(); // 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 simple form-field, then save the form field value in the map. if (diskFileItem.isFormField()) { String characterEncoding = clientDataRequest.getCharacterEncoding(); String requestParameterValue = null; if (characterEncoding == null) { requestParameterValue = diskFileItem.getString(); } else { requestParameterValue = diskFileItem.getString(characterEncoding); } facesRequestParameterMap.addValue(fieldName, requestParameterValue); } else { 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); facesRequestParameterMap.addValue(fieldName, copiedFileAbsolutePath); 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: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 {/* w w w .j av a 2 s . c o 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.liferay.faces.bridge.context.map.MultiPartFormDataProcessorImpl.java
@Override public Map<String, Collection<UploadedFile>> process(ClientDataRequest clientDataRequest, PortletConfig portletConfig, FacesRequestParameterMap facesRequestParameterMap) { Map<String, Collection<UploadedFile>> uploadedFileMap = null; PortletSession portletSession = clientDataRequest.getPortletSession(); String uploadedFilesDir = PortletConfigParam.UploadedFilesDir.getStringValue(portletConfig); // Using the portlet sessionId, determine a unique folder path and create the path if it does not exist. String sessionId = portletSession.getId(); // 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]", StringPool.BLANK); File uploadedFilesPath = new File(uploadedFilesDir, sessionId); if (!uploadedFilesPath.exists()) { uploadedFilesPath.mkdirs();//from w w w . j av a2 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 = PortletConfigParam.UploadedFileMaxSize.getIntegerValue(portletConfig); // Parse the request parameters and save all uploaded files in a map. PortletFileUpload portletFileUpload = new PortletFileUpload(diskFileItemFactory); portletFileUpload.setFileSizeMax(uploadedFileMaxSize); uploadedFileMap = new HashMap<String, Collection<UploadedFile>>(); // FACES-271: Include name+value pairs found in the ActionRequest. Set<Map.Entry<String, String[]>> actionRequestParameterSet = clientDataRequest.getParameterMap().entrySet(); for (Map.Entry<String, String[]> mapEntry : actionRequestParameterSet) { String parameterName = mapEntry.getKey(); String[] parameterValues = mapEntry.getValue(); if (parameterValues.length > 0) { for (String parameterValue : parameterValues) { facesRequestParameterMap.addValue(parameterName, parameterValue); } } } UploadedFileFactory uploadedFileFactory = (UploadedFileFactory) FactoryExtensionFinder .getFactory(UploadedFileFactory.class); // Begin parsing the request for file parts: try { FileItemIterator fileItemIterator = null; if (clientDataRequest instanceof ResourceRequest) { ResourceRequest resourceRequest = (ResourceRequest) clientDataRequest; fileItemIterator = portletFileUpload.getItemIterator(new ActionRequestAdapter(resourceRequest)); } else { ActionRequest actionRequest = (ActionRequest) clientDataRequest; fileItemIterator = portletFileUpload.getItemIterator(actionRequest); } boolean optimizeNamespace = PortletConfigParam.OptimizePortletNamespace.getBooleanValue(portletConfig); if (fileItemIterator != null) { int totalFiles = 0; String namespace = facesRequestParameterMap.getNamespace(); // 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(); // If namespace optimization is enabled and the namespace is present in the field name, // then remove the portlet namespace from the field name. if (optimizeNamespace) { int pos = fieldName.indexOf(namespace); if (pos >= 0) { fieldName = fieldName.substring(pos + namespace.length()); } } // 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 simple form-field, then save the form field value in the map. if (diskFileItem.isFormField()) { String characterEncoding = clientDataRequest.getCharacterEncoding(); String requestParameterValue = null; if (characterEncoding == null) { requestParameterValue = diskFileItem.getString(); } else { requestParameterValue = diskFileItem.getString(characterEncoding); } facesRequestParameterMap.addValue(fieldName, requestParameterValue); } else { 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); facesRequestParameterMap.addValue(fieldName, copiedFileAbsolutePath); 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; }