Search in sources :

Example 16 with FileItemFactory

use of org.apache.commons.fileupload.FileItemFactory in project OpenAttestation by OpenAttestation.

the class WLMDataController method uploadManifest.

public ModelAndView uploadManifest(HttpServletRequest req, HttpServletResponse res) {
    log.info("WLMDataController.uploadManifest >>");
    req.getSession().removeAttribute("manifestValue");
    ModelAndView responseView = new ModelAndView(new JSONView());
    List<Map<String, String>> manifestValue = new ArrayList<Map<String, String>>();
    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);
    System.out.println(isMultipart);
    if (!isMultipart) {
        responseView.addObject("result", false);
        return responseView;
    }
    // Create a factory for disk-based file items
    FileItemFactory factory = new DiskFileItemFactory();
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // Parse the request
    try {
        @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(req);
        // Process the uploaded items
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (!item.isFormField()) {
                String[] lines = item.getString().split("\\r?\\n");
                for (String values : lines) {
                    if (values.length() > 2) {
                        String[] val = values.split(":");
                        if (val.length == 2) {
                            Map<String, String> manifest = new HashMap<String, String>();
                            manifest.put(val[0], val[1]);
                            manifestValue.add(manifest);
                        } else {
                            responseView.addObject("result", false);
                            return responseView;
                        }
                    }
                }
            }
        }
        log.info("Uploaded Content :: " + manifestValue.toString());
        req.getSession().setAttribute("manifestValue", manifestValue);
        /*responseView.addObject("manifestValue",manifestValue);*/
        responseView.addObject("result", manifestValue.size() > 0 ? true : false);
    } catch (FileUploadException e) {
        e.printStackTrace();
        responseView.addObject("result", false);
    } catch (Exception e) {
        e.printStackTrace();
        responseView.addObject("result", false);
    }
    log.info("WLMDataController.uploadManifest <<<");
    return responseView;
}
Also used : HashMap(java.util.HashMap) ModelAndView(org.springframework.web.servlet.ModelAndView) ArrayList(java.util.ArrayList) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItemFactory(org.apache.commons.fileupload.FileItemFactory) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileUploadException(org.apache.commons.fileupload.FileUploadException) WLMPortalException(com.intel.mountwilson.common.WLMPortalException) FileItem(org.apache.commons.fileupload.FileItem) JSONView(com.intel.mountwilson.util.JSONView) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) HashMap(java.util.HashMap) Map(java.util.Map) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 17 with FileItemFactory

use of org.apache.commons.fileupload.FileItemFactory in project libresonic by Libresonic.

the class UploadController method handleRequestInternal.

@RequestMapping(method = { RequestMethod.POST })
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Map<String, Object> map = new HashMap<>();
    List<File> uploadedFiles = new ArrayList<>();
    List<File> unzippedFiles = new ArrayList<>();
    TransferStatus status = null;
    try {
        status = statusService.createUploadStatus(playerService.getPlayer(request, response, false, false));
        status.setBytesTotal(request.getContentLength());
        request.getSession().setAttribute(UPLOAD_STATUS, status);
        // Check that we have a file upload request
        if (!ServletFileUpload.isMultipartContent(request)) {
            throw new Exception("Illegal request.");
        }
        File dir = null;
        boolean unzip = false;
        UploadListener listener = new UploadListenerImpl(status);
        FileItemFactory factory = new MonitoredDiskFileItemFactory(listener);
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<?> items = upload.parseRequest(request);
        // First, look for "dir" and "unzip" parameters.
        for (Object o : items) {
            FileItem item = (FileItem) o;
            if (item.isFormField() && "dir".equals(item.getFieldName())) {
                dir = new File(item.getString());
            } else if (item.isFormField() && "unzip".equals(item.getFieldName())) {
                unzip = true;
            }
        }
        if (dir == null) {
            throw new Exception("Missing 'dir' parameter.");
        }
        // Look for file items.
        for (Object o : items) {
            FileItem item = (FileItem) o;
            if (!item.isFormField()) {
                String fileName = item.getName();
                if (fileName.trim().length() > 0) {
                    File targetFile = new File(dir, new File(fileName).getName());
                    if (!securityService.isUploadAllowed(targetFile)) {
                        throw new Exception("Permission denied: " + StringUtil.toHtml(targetFile.getPath()));
                    }
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }
                    item.write(targetFile);
                    uploadedFiles.add(targetFile);
                    LOG.info("Uploaded " + targetFile);
                    if (unzip && targetFile.getName().toLowerCase().endsWith(".zip")) {
                        unzip(targetFile, unzippedFiles);
                    }
                }
            }
        }
    } catch (Exception x) {
        LOG.warn("Uploading failed.", x);
        map.put("exception", x);
    } finally {
        if (status != null) {
            statusService.removeUploadStatus(status);
            request.getSession().removeAttribute(UPLOAD_STATUS);
            User user = securityService.getCurrentUser(request);
            securityService.updateUserByteCounts(user, 0L, 0L, status.getBytesTransfered());
        }
    }
    map.put("uploadedFiles", uploadedFiles);
    map.put("unzippedFiles", unzippedFiles);
    return new ModelAndView("upload", "model", map);
}
Also used : User(org.libresonic.player.domain.User) ModelAndView(org.springframework.web.servlet.ModelAndView) UploadListener(org.libresonic.player.upload.UploadListener) FileItemFactory(org.apache.commons.fileupload.FileItemFactory) MonitoredDiskFileItemFactory(org.libresonic.player.upload.MonitoredDiskFileItemFactory) FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) TransferStatus(org.libresonic.player.domain.TransferStatus) MonitoredDiskFileItemFactory(org.libresonic.player.upload.MonitoredDiskFileItemFactory) ZipFile(org.apache.tools.zip.ZipFile) File(java.io.File) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 18 with FileItemFactory

use of org.apache.commons.fileupload.FileItemFactory in project libresonic by Libresonic.

the class AvatarUploadController method handleRequestInternal.

@RequestMapping(method = RequestMethod.POST)
protected ModelAndView handleRequestInternal(HttpServletRequest request) throws Exception {
    String username = securityService.getCurrentUsername(request);
    // Check that we have a file upload request.
    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new Exception("Illegal request.");
    }
    Map<String, Object> map = new HashMap<String, Object>();
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<?> items = upload.parseRequest(request);
    // Look for file items.
    for (Object o : items) {
        FileItem item = (FileItem) o;
        if (!item.isFormField()) {
            String fileName = item.getName();
            byte[] data = item.get();
            if (StringUtils.isNotBlank(fileName) && data.length > 0) {
                createAvatar(fileName, data, username, map);
            } else {
                map.put("error", new Exception("Missing file."));
                LOG.warn("Failed to upload personal image. No file specified.");
            }
            break;
        }
    }
    map.put("username", username);
    map.put("avatar", settingsService.getCustomAvatar(username));
    return new ModelAndView("avatarUploadResult", "model", map);
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) HashMap(java.util.HashMap) ModelAndView(org.springframework.web.servlet.ModelAndView) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) IOException(java.io.IOException) FileItemFactory(org.apache.commons.fileupload.FileItemFactory) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 19 with FileItemFactory

use of org.apache.commons.fileupload.FileItemFactory in project jspwiki by apache.

the class AttachmentServlet method upload.

/**
 *  Uploads a specific mime multipart input set, intercepts exceptions.
 *
 *  @param req The servlet request
 *  @return The page to which we should go next.
 *  @throws RedirectException If there's an error and a redirection is needed
 *  @throws IOException If upload fails
 * @throws FileUploadException
 */
protected String upload(HttpServletRequest req) throws RedirectException, IOException {
    String msg = "";
    String attName = "(unknown)";
    // If something bad happened, Upload should be able to take care of most stuff
    String errorPage = m_engine.getURL(WikiContext.ERROR, "", null, false);
    String nextPage = errorPage;
    String progressId = req.getParameter("progressid");
    // Check that we have a file upload request
    if (!ServletFileUpload.isMultipartContent(req)) {
        throw new RedirectException("Not a file upload", errorPage);
    }
    try {
        FileItemFactory factory = new DiskFileItemFactory();
        // Create the context _before_ Multipart operations, otherwise
        // strict servlet containers may fail when setting encoding.
        WikiContext context = m_engine.createContext(req, WikiContext.ATTACH);
        UploadListener pl = new UploadListener();
        m_engine.getProgressManager().startProgress(pl, progressId);
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");
        if (!context.hasAdminPermissions()) {
            upload.setFileSizeMax(m_maxSize);
        }
        upload.setProgressListener(pl);
        List<FileItem> items = upload.parseRequest(req);
        String wikipage = null;
        String changeNote = null;
        // FileItem actualFile = null;
        List<FileItem> fileItems = new java.util.ArrayList<FileItem>();
        for (FileItem item : items) {
            if (item.isFormField()) {
                if (item.getFieldName().equals("page")) {
                    // 
                    // FIXME: Kludge alert.  We must end up with the parent page name,
                    // if this is an upload of a new revision
                    // 
                    wikipage = item.getString("UTF-8");
                    int x = wikipage.indexOf("/");
                    if (x != -1)
                        wikipage = wikipage.substring(0, x);
                } else if (item.getFieldName().equals("changenote")) {
                    changeNote = item.getString("UTF-8");
                    if (changeNote != null) {
                        changeNote = TextUtil.replaceEntities(changeNote);
                    }
                } else if (item.getFieldName().equals("nextpage")) {
                    nextPage = validateNextPage(item.getString("UTF-8"), errorPage);
                }
            } else {
                fileItems.add(item);
            }
        }
        if (fileItems.size() == 0) {
            throw new RedirectException("Broken file upload", errorPage);
        } else {
            for (FileItem actualFile : fileItems) {
                String filename = actualFile.getName();
                long fileSize = actualFile.getSize();
                InputStream in = actualFile.getInputStream();
                try {
                    executeUpload(context, in, filename, nextPage, wikipage, changeNote, fileSize);
                } finally {
                    IOUtils.closeQuietly(in);
                }
            }
        }
    } catch (ProviderException e) {
        msg = "Upload failed because the provider failed: " + e.getMessage();
        log.warn(msg + " (attachment: " + attName + ")", e);
        throw new IOException(msg);
    } catch (IOException e) {
        // Show the submit page again, but with a bit more
        // intimidating output.
        msg = "Upload failure: " + e.getMessage();
        log.warn(msg + " (attachment: " + attName + ")", e);
        throw e;
    } catch (FileUploadException e) {
        // Show the submit page again, but with a bit more
        // intimidating output.
        msg = "Upload failure: " + e.getMessage();
        log.warn(msg + " (attachment: " + attName + ")", e);
        throw new IOException(msg, e);
    } finally {
        m_engine.getProgressManager().stopProgress(progressId);
    // FIXME: In case of exceptions should absolutely
    // remove the uploaded file.
    }
    return nextPage;
}
Also used : WikiContext(org.apache.wiki.WikiContext) ProviderException(org.apache.wiki.api.exceptions.ProviderException) InputStream(java.io.InputStream) IOException(java.io.IOException) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItemFactory(org.apache.commons.fileupload.FileItemFactory) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileUploadException(org.apache.commons.fileupload.FileUploadException) RedirectException(org.apache.wiki.api.exceptions.RedirectException)

Example 20 with FileItemFactory

use of org.apache.commons.fileupload.FileItemFactory in project activityinfo by bedatadriven.

the class AttachmentServlet method getFirstUploadFile.

private FileItem getFirstUploadFile(HttpServletRequest request) throws FileUploadException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        FileItemFactory factory = service.createFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = upload.parseRequest(request);
        for (FileItem item : items) {
            return item;
        }
    }
    throw new RuntimeException("No upload provided");
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileItemFactory(org.apache.commons.fileupload.FileItemFactory)

Aggregations

FileItemFactory (org.apache.commons.fileupload.FileItemFactory)27 ServletFileUpload (org.apache.commons.fileupload.servlet.ServletFileUpload)27 DiskFileItemFactory (org.apache.commons.fileupload.disk.DiskFileItemFactory)24 FileItem (org.apache.commons.fileupload.FileItem)23 FileUploadException (org.apache.commons.fileupload.FileUploadException)16 HashMap (java.util.HashMap)9 IOException (java.io.IOException)7 ArrayList (java.util.ArrayList)6 List (java.util.List)6 JSONObject (org.json.JSONObject)6 ApplicationContext (org.springframework.context.ApplicationContext)6 File (java.io.File)5 InputStream (java.io.InputStream)5 ServletException (javax.servlet.ServletException)5 ILogEventService (org.cerberus.crud.service.ILogEventService)5 MessageEvent (org.cerberus.engine.entity.MessageEvent)5 Answer (org.cerberus.util.answer.Answer)5 Iterator (java.util.Iterator)4 AnswerItem (org.cerberus.util.answer.AnswerItem)4 BufferedReader (java.io.BufferedReader)3