public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); FileItemIterator iterator = null; try { iterator = upload.getItemIterator(request); while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream in = item.openStream(); if (item.getFieldName().equals("bundleUpload")) { String fname = item.getName(); if (!fname.endsWith(".jar")) { Logger.warn(this, "Cannot deplpy bundle as it is not a JAR"); writeError(response, "Cannot deplpy bundle as it is not a JAR"); break; } File to = new File(Config.CONTEXT.getRealPath("/WEB-INF/felix/load/" + fname)); FileOutputStream out = new FileOutputStream(to); IOUtils.copyLarge(in, out); IOUtils.closeQuietly(out); IOUtils.closeQuietly(in); } } } catch (FileUploadException e) { Logger.error(OSGIBaseAJAX.class, e.getMessage(), e); throw new IOException(e.getMessage(), e); } }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { super.doPost(request, response); try { if (!ServletFileUpload.isMultipartContent(request)) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } ServletFileUpload sfU = new ServletFileUpload(); FileItemIterator items = sfU.getItemIterator(request); while (items.hasNext()) { FileItemStream item = items.next(); if (!item.isFormField()) { InputStream stream = item.openStream(); Document doc = editor.toDocument(stream); stream.close(); handleDocument(request, response, doc); return; } } response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No XML uploaded"); } catch (FileUploadException fuE) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, fuE.getMessage()); } catch (JDOMException jE) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, jE.getMessage()); } }
@SuppressWarnings("unchecked") @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.info("upload start------"); request.setCharacterEncoding("UTF-8"); StringBuffer savePath = new StringBuffer("/mnt/web/static/images/album/"); Calendar c = Calendar.getInstance(); DateFormat df = new SimpleDateFormat("yyyy/MM/dd/"); String date = df.format(c.getTime()); savePath.append(date); File dir = new File(savePath.toString()); if (!dir.exists()) { dir.mkdirs(); } DiskFileItemFactory fac = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(fac); upload.setHeaderEncoding("UTF-8"); List<FileItem> list = null; try { list = upload.parseRequest(request); } catch (FileUploadException e) { log.error(e.getMessage(), e); return; } log.info("file size:{}", list.size()); for (FileItem it : list) { if (!it.isFormField()) { String name = it.getName(); long size = it.getSize(); String type = it.getContentType(); log.info("name:{},size:{},type:{}", name, size, type); if (StringUtils.isBlank(name)) { continue; } String extName = null; if (name.lastIndexOf(".") >= 0) { extName = name.substring(name.lastIndexOf(".")); } File file = null; do { name = UUIDUtil.getRandomUUID(); file = new File(savePath + name + extName); } while (file.exists()); File saveFile = new File(savePath + name + extName); log.info("path:{}", saveFile.getAbsolutePath()); try { it.write(saveFile); albumService.newPhoto(1, saveFile.getAbsolutePath(), "none"); } catch (Exception e) { e.printStackTrace(); } } } response.getWriter().write("1"); log.info("upload end------"); }
/** * Creates a new request wrapper to handle multi-part data using methods adapted from Jason Pell's * multipart classes (see class description). * * @param saveDir the directory to save off the file * @param request the request containing the multipart * @throws java.io.IOException is thrown if encoding fails. */ public void parse(HttpServletRequest request, String saveDir) throws IOException { try { processUpload(request, saveDir); } catch (FileUploadException e) { if (LOG.isWarnEnabled()) { LOG.warn("Unable to parse request", e); } errors.add(e.getMessage()); } }
@POST @Path("{type:user|group}/{userid}") public Response doUpdateAuthorizable( @Context HttpServletRequest request, @Context HttpServletResponse response, @PathParam(value = "type") String authorizableType, @PathParam(value = "userid") String authorizableId) { try { AuthorizableManager authorizableManager = getAuthorizableManager(request, response); Authorizable authorizable = authorizableManager.findAuthorizable(authorizableId); Response checkType = checkType(authorizable, authorizableType); if (checkType != null) { return checkType; } // process the post request. AuthorizableHelper authorizableHelper = new AuthorizableHelper(authorizableManager); ModificationRequest modificationRequest = new ModificationRequest(); modificationRequest.processRequest(request); authorizableHelper.applyProperties(authorizable, modificationRequest); authorizableHelper.save(); final List<String> feedback = modificationRequest.getFeedback(); return Response.ok( new StreamingOutput() { @Override public void write(OutputStream output) throws IOException, WebApplicationException { ResponseUtils.writeFeedback(feedback, output); } }) .type(MediaType.APPLICATION_JSON_TYPE.toString() + "; charset=utf-8") .lastModified(new Date()) .build(); } catch (StorageClientException e) { return ResponseUtils.getResponse( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } catch (AccessDeniedException e) { return ResponseUtils.getResponse(HttpServletResponse.SC_FORBIDDEN, e.getMessage()); } catch (IOException e) { return ResponseUtils.getResponse( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } catch (FileUploadException e) { return ResponseUtils.getResponse( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } }
@Override public void processAction(ActionRequest request, ActionResponse response) throws IOException, PortletException { ActionRequest myRequest = request; if (FileUploadUtil.isMultipart(request)) { // logger.info("multipart!"); try { myRequest = new FileUploadActionRequestWrapper(request); } catch (FileUploadException e) { logger.error(e.getMessage()); } } super.processAction(myRequest, response); }
@POST @Path("port") @Consumes(MediaType.MULTIPART_FORM_DATA) public void importData(@Context HttpServletRequest request) throws IcatException, IOException { if (!ServletFileUpload.isMultipartContent(request)) { throw new IcatException(IcatExceptionType.BAD_PARAMETER, "Multipart content expected"); } ServletFileUpload upload = new ServletFileUpload(); String jsonString = null; String name = null; // Parse the request try { FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String fieldName = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { String value = Streams.asString(stream); if (fieldName.equals("json")) { jsonString = value; } else { throw new IcatException( IcatExceptionType.BAD_PARAMETER, "Form field " + fieldName + "is not recognised"); } } else { if (name == null) { name = item.getName(); } porter.importData(jsonString, stream, manager, userTransaction); } } } catch (FileUploadException e) { throw new IcatException(IcatExceptionType.INTERNAL, e.getClass() + " " + e.getMessage()); } }
void onUploadException(FileUploadException ex) { message = "Upload exception: " + ex.getMessage(); ajaxResponseRenderer.addRender("uploadResult", uploadResult); }
/** * Process the blog entries * * @param httpServletRequest Request * @param httpServletResponse Response * @param user {@link org.blojsom.blog.BlogUser} instance * @param context Context * @param entries Blog entries retrieved for the particular request * @return Modified set of blog entries * @throws BlojsomPluginException If there is an error processing the blog entries */ public BlogEntry[] process( HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlogUser user, Map context, BlogEntry[] entries) throws BlojsomPluginException { if (!authenticateUser(httpServletRequest, httpServletResponse, context, user)) { httpServletRequest.setAttribute(PAGE_PARAM, ADMIN_LOGIN_PAGE); return entries; } String username = getUsernameFromSession(httpServletRequest, user.getBlog()); if (!checkPermission(user, null, username, FILE_UPLOAD_PERMISSION)) { httpServletRequest.setAttribute(PAGE_PARAM, ADMIN_ADMINISTRATION_PAGE); addOperationResultMessage(context, "You are not allowed to upload files"); return entries; } File resourceDirectory = new File( _blojsomConfiguration.getInstallationDirectory() + _resourcesDirectory + user.getId() + "/"); String action = BlojsomUtils.getRequestValue(ACTION_PARAM, httpServletRequest); if (BlojsomUtils.checkNullOrBlank(action)) { _logger.debug("User did not request edit action"); httpServletRequest.setAttribute(PAGE_PARAM, ADMIN_ADMINISTRATION_PAGE); } else if (PAGE_ACTION.equals(action)) { _logger.debug("User requested file upload page"); httpServletRequest.setAttribute(PAGE_PARAM, FILE_UPLOAD_PAGE); } else if (UPLOAD_FILE_ACTION.equals(action)) { _logger.debug("User requested file upload action"); // Create a new disk file upload and set its parameters DiskFileUpload diskFileUpload = new DiskFileUpload(); diskFileUpload.setRepositoryPath(_temporaryDirectory); diskFileUpload.setSizeThreshold(_maximumMemorySize); diskFileUpload.setSizeMax(_maximumUploadSize); try { List items = diskFileUpload.parseRequest(httpServletRequest); Iterator itemsIterator = items.iterator(); while (itemsIterator.hasNext()) { FileItem item = (FileItem) itemsIterator.next(); // Check for the file upload form item if (!item.isFormField()) { String itemNameWithoutPath = BlojsomUtils.getFilenameFromPath(item.getName()); _logger.debug( "Found file item: " + itemNameWithoutPath + " of type: " + item.getContentType()); // Is it one of the accepted file types? String fileType = item.getContentType(); boolean isAcceptedFileType = _acceptedFileTypes.containsKey(fileType); String extension = BlojsomUtils.getFileExtension(itemNameWithoutPath); boolean isAcceptedFileExtension = true; for (int i = 0; i < _invalidFileExtensions.length; i++) { String invalidFileExtension = _invalidFileExtensions[i]; if (itemNameWithoutPath.indexOf(invalidFileExtension) != -1) { isAcceptedFileExtension = false; break; } } // If so, upload the file to the resources directory if (isAcceptedFileType && isAcceptedFileExtension) { if (!resourceDirectory.exists()) { if (!resourceDirectory.mkdirs()) { _logger.error( "Unable to create resource directory for user: "******"Unable to create resource directory"); return entries; } } File resourceFile = new File( _blojsomConfiguration.getInstallationDirectory() + _resourcesDirectory + user.getId() + "/" + itemNameWithoutPath); try { item.write(resourceFile); } catch (Exception e) { _logger.error(e); addOperationResultMessage( context, "Unknown error in file upload: " + e.getMessage()); } String resourceURL = user.getBlog().getBlogBaseURL() + _blojsomConfiguration.getResourceDirectory() + user.getId() + "/" + item.getName(); _logger.debug("Successfully uploaded resource file: " + resourceFile.toString()); addOperationResultMessage( context, "Successfully upload resource file: " + item.getName() + ". <p></p>Here is a link to <a href=\"" + resourceURL + "\">" + item.getName() + "</a>. Right-click and copy the link to the resource to use in a blog entry."); } else { if (!isAcceptedFileExtension) { _logger.error("Upload file does not have an accepted extension: " + extension); addOperationResultMessage( context, "Upload file does not have an accepted extension: " + extension); } else { _logger.error( "Upload file is not an accepted type: " + item.getName() + " of type: " + item.getContentType()); addOperationResultMessage( context, "Upload file is not an accepted type: " + item.getName() + " of type: " + item.getContentType()); } } } } } catch (FileUploadException e) { _logger.error(e); addOperationResultMessage(context, "Unknown error in file upload: " + e.getMessage()); } httpServletRequest.setAttribute(PAGE_PARAM, FILE_UPLOAD_PAGE); } else if (DELETE_UPLOAD_FILES.equals(action)) { String[] filesToDelete = httpServletRequest.getParameterValues(FILE_TO_DELETE); if (filesToDelete != null && filesToDelete.length > 0) { File deletedFile; for (int i = 0; i < filesToDelete.length; i++) { String fileToDelete = filesToDelete[i]; deletedFile = new File(resourceDirectory, fileToDelete); if (!deletedFile.delete()) { _logger.debug("Unable to delete resource file: " + deletedFile.toString()); } } addOperationResultMessage( context, "Deleted " + filesToDelete.length + " file(s) from resources directory"); } httpServletRequest.setAttribute(PAGE_PARAM, FILE_UPLOAD_PAGE); } // Create a list of files in the user's resource directory Map resourceFilesMap = null; if (resourceDirectory.exists()) { File[] resourceFiles = resourceDirectory.listFiles(); if (resourceFiles != null) { resourceFilesMap = new HashMap(resourceFiles.length); for (int i = 0; i < resourceFiles.length; i++) { File resourceFile = resourceFiles[i]; resourceFilesMap.put(resourceFile.getName(), resourceFile.getName()); } } } else { resourceFilesMap = new HashMap(); } resourceFilesMap = new TreeMap(resourceFilesMap); context.put(PLUGIN_ADMIN_FILE_UPLOAD_FILES, resourceFilesMap); return entries; }
/** * Creates a new request wrapper to handle multi-part data using methods adapted from Jason Pell's * multipart classes (see class description). * * @param saveDir the directory to save off the file * @param servletRequest the request containing the multipart * @throws java.io.IOException is thrown if encoding fails. */ @SuppressWarnings("unchecked") @Override public void parse(HttpServletRequest servletRequest, String saveDir) throws IOException { DiskFileItemFactory fac = new DiskFileItemFactory(); // Make sure that the data is written to file fac.setSizeThreshold(0); if (saveDir != null) { fac.setRepository(new File(saveDir)); } ProgressMonitor monitor = null; // Parse the request try { ServletFileUpload upload = new ServletFileUpload(fac); upload.setSizeMax(maxSize); monitor = new ProgressMonitor(); upload.setProgressListener(monitor); servletRequest.getSession().setAttribute(ProgressMonitor.SESSION_PROGRESS_MONITOR, monitor); List<FileItem> items = upload.parseRequest(createRequestContext(servletRequest)); for (FileItem item1 : items) { FileItem item = item1; if (log.isDebugEnabled()) { log.debug("Found item " + item.getFieldName()); } if (item.isFormField()) { if (log.isDebugEnabled()) { log.debug("Item is a normal form field"); } List<String> values; if (params.get(item.getFieldName()) != null) { values = params.get(item.getFieldName()); } else { values = new ArrayList<String>(); } // note: see http://jira.opensymphony.com/browse/WW-633 // basically, in some cases the charset may be null, so // we're just going to try to "other" method (no idea if this // will work) String charset = servletRequest.getCharacterEncoding(); if (charset != null) { values.add(item.getString(charset)); } else { values.add(item.getString()); } params.put(item.getFieldName(), values); } else { if (log.isDebugEnabled()) { log.debug("Item is a file upload"); } List<FileItem> values; if (files.get(item.getFieldName()) != null) { values = files.get(item.getFieldName()); } else { values = new ArrayList<FileItem>(); } values.add(item); files.put(item.getFieldName(), values); } } } catch (FileUploadException e) { e.printStackTrace(); if (monitor != null) monitor.abort(); log.error(e); errors.add(e.getMessage()); } catch (Exception e) { e.printStackTrace(); if (monitor != null) monitor.abort(); } }
public Object onUploadException(FileUploadException exception) { message = "Upload exception: " + exception.getMessage(); return this; }
/** * This method will upload files and store them under the dest_path. * * <p>File names are formed by <thread_name>_<counter>_originalFileName * * <p>The returned hashmap contains a list of name value pairs, where a value * * <p>can either be normal form input parameter or the uploaded file path. * * @param HttpServletRequest request * @param String dest_path upload destination path * @return HashMap */ public static HashMap parseMultipartRequest(HttpServletRequest request, String dest_path) { HashMap hmfield = new HashMap(); String threadname = Thread.currentThread().getName(); RequestContext requestContext = new ServletRequestContext(request); int filemaxsize = LPropertyManager.getInt("file.upload.maxsize", 2000000); if (FileUpload.isMultipartContent(requestContext)) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(new File(dest_path)); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(filemaxsize); List items = new ArrayList(); try { items = upload.parseRequest(request); } catch (FileUploadException e1) { gLogger.fatalize("LUploadUtil", e1.getMessage()); } Iterator it = items.iterator(); while (it.hasNext()) { FileItem fileItem = (FileItem) it.next(); if (fileItem.isFormField()) { hmfield.put(fileItem.getFieldName(), fileItem.getString()); } else { if (fileItem.getName() != null && fileItem.getSize() != 0) { File fullFile = new File(fileItem.getName()); String tempfile = dest_path + File.separator + threadname + "_" + tick() + "_" + fullFile.getName(); hmfield.put(fileItem.getFieldName(), tempfile); hmfield.put("originalfilename", fullFile.getName()); File newFile = new File(tempfile); try { fileItem.write(newFile); } catch (Exception e) { gLogger.fatalize("LUploadUtil", e.getMessage()); } } else { gLogger.errorLog("No file is selected or the file is empty!"); } } } } return hmfield; }
@SuppressWarnings("unchecked") private void initParamsIfNeeded() { if (!isParamInitialized) { isMultipart = ServletFileUpload.isMultipartContent(getReq()); if (isMultipart) { try { fileItems = fileUploader.parseRequest(getReq()); paramMap = new HashMap<String, Object>(); boolean hasMultivalues = false; for (Object item : fileItems) { FileItem fileItem = (FileItem) item; String paramName = fileItem.getFieldName(); if (fileItem.isFormField()) { String value = fileItem.getString(); // if there is already a value, then, create a list if (paramMap.containsKey(paramName)) { hasMultivalues = true; Object prevValue = paramMap.get(paramName); if (prevValue instanceof List) { ((List) prevValue).add(value); } else { List<String> values = new ArrayList<String>(2); values.add((String) prevValue); values.add(value); paramMap.put(paramName, values); } } else { paramMap.put(paramName, value); } } else { paramMap.put(paramName, fileItem); } } // if we had multivalues, need to change the list to arrays if (hasMultivalues) { for (String name : paramMap.keySet()) { Object value = paramMap.get(name); if (value instanceof List) { List<String> valueList = (List<String>) value; String[] valueArray = new String[valueList.size()]; valueList.toArray(valueArray); paramMap.put(name, valueArray); } } } } catch (FileUploadException e) { // TODO Auto-generated catch block logger.error(e.getMessage()); } } else { paramMap = new HashMap<String, Object>(); // By the httpServletRequest spect, we can assume the type of // the return Map (name and values) Map<String, String[]> reqMap = getReq().getParameterMap(); // now, simplify the map, by replacing single string array to // the string itself. for (String paramName : reqMap.keySet()) { String[] values = reqMap.get(paramName); if (values.length == 1) { paramMap.put(paramName, values[0]); } else { paramMap.put(paramName, values); } } } isParamInitialized = true; } }
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * <p>This servlet is used to insert into db for a service posted by a user * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { // multipart handling for image from service boolean isMultipart = ServletFileUpload.isMultipartContent(request); String OSDataFolder = System.getenv("OPENSHIFT_DATA_DIR"); File uploadedFile = null; if (!isMultipart) { JSONObject service = new JSONObject((String) request.getParameter("service")); ServiceDAO sd = new ServiceDAO(); boolean success = sd.addService(service); out.println(success); } else { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); try { // Parse the request List<FileItem> items = upload.parseRequest(request); Iterator iterator = items.iterator(); while (iterator.hasNext()) { FileItem item = (FileItem) iterator.next(); if (!item.isFormField()) { if (OSDataFolder == null) { String root = getServletContext().getRealPath("/"); File path = new File(root + "/" + item.getFieldName()); System.out.println( "itemname: " + item.getName() + " fieldname: " + item.getFieldName()); if (!path.exists()) { boolean status = path.mkdirs(); } uploadedFile = new File(path + "/" + item.getName() + ".png"); } else { String root = OSDataFolder; File path = new File(root); if (!path.exists()) { boolean status = path.mkdirs(); } uploadedFile = new File(path + "/" + item.getFieldName() + ".png"); // imageLink = uploadedFile.getAbsolutePath(); } item.write(uploadedFile); } } } catch (FileUploadException e) { e.printStackTrace(); e.getMessage(); out.println(e); } catch (Exception e) { e.printStackTrace(); e.getMessage(); out.println(e); } } } catch (Exception e) { } finally { out.close(); } }