Example usage for org.apache.commons.fileupload FileUploadException printStackTrace

List of usage examples for org.apache.commons.fileupload FileUploadException printStackTrace

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileUploadException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:hd.controller.AddImageToProductServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* ww w  .j  a va2  s . com*/
 *
 * @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 {
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart) { //to do

        } else {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = null;
            try {
                items = upload.parseRequest(request);

            } catch (FileUploadException e) {
                e.printStackTrace();
            }
            Iterator iter = items.iterator();
            Hashtable params = new Hashtable();

            String fileName = null;
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField()) {
                    params.put(item.getFieldName(), item.getString("UTF-8"));

                } else if (!item.isFormField()) {
                    try {
                        long time = System.currentTimeMillis();
                        String itemName = item.getName();
                        fileName = time + itemName.substring(itemName.lastIndexOf("\\") + 1);
                        String RealPath = getServletContext().getRealPath("/") + "images\\" + fileName;
                        File savedFile = new File(RealPath);
                        item.write(savedFile);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }
            String productID = (String) params.get("txtProductId");
            System.out.println(productID);
            String tilte = (String) params.get("newGalleryName");
            String description = (String) params.get("GalleryDescription");
            String url = "images/" + fileName;
            ProductDAO productDao = new ProductDAO();
            ProductPhoto productPhoto = productDao.insertProductPhoto(tilte, description, url, productID);

            response.sendRedirect("MyProductDetailServlet?action=showDetail&txtProductID=" + productID);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        out.close();
    }
}

From source file:cdc.util.Upload.java

public boolean anexos(HttpServletRequest request) throws Exception {
    request.setCharacterEncoding("ISO-8859-1");
    if (ServletFileUpload.isMultipartContent(request)) {
        int cont = 0;
        ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
        List fileItemsList = null;
        try {/* w w  w.j av a2s.  c  o  m*/
            fileItemsList = servletFileUpload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        String optionalFileName = "";
        FileItem fileItem = null;
        Iterator it = fileItemsList.iterator();
        do {
            //cont++;
            FileItem fileItemTemp = (FileItem) it.next();
            if (fileItemTemp.isFormField()) {
                if (fileItemTemp.getFieldName().equals("file")) {
                    optionalFileName = fileItemTemp.getString();
                }
                parametros.put(fileItemTemp.getFieldName(), fileItemTemp.getString());
            } else {
                fileItem = fileItemTemp;
            }
            if (cont != (fileItemsList.size())) {
                if (fileItem != null) {
                    String fileName = fileItem.getName();
                    if (fileItem.getSize() > 0) {
                        if (optionalFileName.trim().equals("")) {
                            fileName = FilenameUtils.getName(fileName);
                        } else {
                            fileName = optionalFileName;
                        }
                        String dirName = request.getServletContext().getRealPath(pasta);
                        File saveTo = new File(dirName + "/" + fileName);
                        //verificando se a pasta existe. Caso contrrio, criar ela
                        File pasta = new File(dirName);
                        if (!pasta.exists())
                            pasta.mkdirs();//criando a pasta

                        parametros.put("foto", fileName);

                        try {
                            fileItem.write(saveTo);//Escrevendo o arquivo temporrio no diretrio correto
                        } catch (Exception e) {
                        }
                    }
                }
            }
            cont++;
        } while (it.hasNext());
        return true;
    } else {
        return false;
    }
}

From source file:com.lemania.sis.server.servlet.GcsServlet.java

/**
 * Writes the payload of the incoming post as the contents of a file to GCS.
 * If the request path is /gcs/Foo/Bar this will be interpreted as a request
 * to create a GCS file named Bar in bucket Foo.
 * //from  w  w  w  . jav  a 2  s  .  c o  m
 * @throws ServletException
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    //
    GcsOutputChannel outputChannel = gcsService.createOrReplace(getFileName(req),
            GcsFileOptions.getDefaultInstance());

    ServletFileUpload upload = new ServletFileUpload();
    resp.setContentType("text/plain");
    //
    InputStream fileContent = null;
    FileItemIterator iterator;
    try {
        iterator = upload.getItemIterator(req);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            InputStream stream = item.openStream();

            if (item.isFormField()) {
                //
            } else {
                fileContent = stream;
                break;
            }
        }
    } catch (FileUploadException e) {
        //
        e.printStackTrace();
    }
    //
    copy(fileContent, Channels.newOutputStream(outputChannel));
}

From source file:br.gov.jfrj.siga.wf.servlet.UploadServlet.java

/**
 * Verifica se o arquivo enviado  um process definition. Se for, realiza o
 * seu deploy./*from ww  w.  j  av  a 2  s  .c o m*/
 * 
 * @param request
 * @return
 */
private String handleRequest(HttpServletRequest request) {
    if (!FileUpload.isMultipartContent(request)) {
        log.debug("Not a multipart request");
        return "Not a multipart request";
    }
    try {
        // Nato: Modo novo, mas que esta voltando uma lista vazia pois o
        // webwork est interceptando o request e lendo o arquivo
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // Configure the factory here, if desired.
        ServletFileUpload upload = new ServletFileUpload(factory);
        // Configure the uploader here, if desired.
        List list = upload.parseRequest(request);

        // Nato: modo antigo
        // DiskFileUpload fileUpload = new DiskFileUpload();
        // List list = fileUpload.parseRequest(request);

        // MultiPartRequestWrapper req = (MultiPartRequestWrapper)request;
        // req.get

        Iterator iterator = list.iterator();
        if (!iterator.hasNext()) {
            log.debug("No process file in the request");
            return "No process file in the request";
        }
        FileItem fileItem = (FileItem) iterator.next();
        if (fileItem.getContentType().indexOf("application/x-zip-compressed") == -1) {
            log.debug("Not a process archive");
            return "Not a process archive";
        }
        return doDeployment(fileItem);
    } catch (FileUploadException e) {
        e.printStackTrace();
        return "FileUploadException";
    } catch (Exception e) {
        e.printStackTrace();
        throw new Error(e);
    }
}

From source file:com.tasktop.c2c.server.tasks.web.service.AttachmentUploadController.java

@RequestMapping(value = "", method = RequestMethod.POST)
public void upload(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, TextHtmlContentExceptionWrapper {
    try {/*from  w ww  .  ja v  a 2 s. c  o m*/
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<Attachment> attachments = new ArrayList<Attachment>();
        Map<String, String> formValues = new HashMap<String, String>();

        try {
            List<FileItem> items = upload.parseRequest(request);

            for (FileItem item : items) {

                if (item.isFormField()) {
                    formValues.put(item.getFieldName(), item.getString());
                } else {
                    Attachment attachment = new Attachment();
                    attachment.setAttachmentData(readInputStream(item.getInputStream()));
                    attachment.setFilename(item.getName());
                    attachment.setMimeType(item.getContentType());
                    attachments.add(attachment);
                }

            }
        } catch (FileUploadException e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); // FIXME better code
            return;
        }

        for (int i = 0; i < attachments.size(); i++) {
            String description = formValues
                    .get(AttachmentUploadUtil.ATTACHMENT_DESCRIPTION_FORM_NAME_PREFIX + i);
            if (description == null) {
                throw new IllegalArgumentException(
                        "Missing description " + i + 1 + " of " + attachments.size());
            }
            attachments.get(0).setDescription(description);
        }

        TaskHandle taskHandle = getTaskHandle(formValues);

        UploadResult result = doUpload(response, attachments, taskHandle);

        response.setContentType("text/html");
        response.getWriter()
                .write(jsonMapper.writeValueAsString(Collections.singletonMap("uploadResult", result)));
    } catch (Exception e) {
        throw new TextHtmlContentExceptionWrapper(e.getMessage(), e);
    }
}

From source file:massbank.FileUpload.java

/**
 * NGXgp??[^?//  www  . j  av a2 s  .c o  m
 * multipart/form-data?NGXg?
 * s??nullp
 * @return ?NGXg?MAP<L?[, l>
 */
@SuppressWarnings("unchecked")
public HashMap<String, String[]> getRequestParam() {

    if (fileItemList == null) {
        try {
            fileItemList = (List<FileItem>) parseRequest(req);
        } catch (FileUploadException e) {
            e.printStackTrace();
            return null;
        }
    }

    HashMap<String, String[]> reqParamMap = new HashMap<String, String[]>();
    for (FileItem fItem : fileItemList) {

        // ?tB?[h???iNGXgp??[^lz???j
        if (fItem.isFormField()) {
            String key = fItem.getFieldName();
            String val = fItem.getString();
            if (key != null && !key.equals("")) {
                reqParamMap.put(key, new String[] { val });
            }
        }
    }
    return reqParamMap;
}

From source file:mx.org.cedn.avisosconagua.engine.processors.Pronostico.java

@Override
public void processForm(HttpServletRequest request, String[] parts, String currentId)
        throws ServletException, IOException {
    HashMap<String, String> parametros = new HashMap<>();
    boolean fileflag = false;
    AvisosException aex = null;// w ww . jav  a  2s .  co  m
    if (ServletFileUpload.isMultipartContent(request)) {
        try {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(MAX_SIZE);
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setSizeMax(MAX_SIZE);
            List<FileItem> items = upload.parseRequest(request);
            String filename = null;
            for (FileItem item : items) {
                if (!item.isFormField() && item.getSize() > 0) {
                    filename = processUploadedFile(item, currentId);
                    parametros.put(item.getFieldName(), filename);
                } else {
                    //System.out.println("item:" + item.getFieldName() + "=" + item.getString());
                    parametros.put(item.getFieldName(),
                            new String(item.getString().getBytes("ISO8859-1"), "UTF-8"));
                }
            }
        } catch (FileUploadException fue) {
            fue.printStackTrace();
            fileflag = true;
            aex = new AvisosException("El archivo sobrepasa el tamao de " + MAX_SIZE + " bytes", fue);
        }
    } else {
        for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
            try {
                parametros.put(entry.getKey(),
                        new String(request.getParameter(entry.getKey()).getBytes("ISO8859-1"), "UTF-8"));
            } catch (UnsupportedEncodingException ue) {
                //No debe llegar a este punto
                assert false;
            }
        }
    }
    BasicDBObject anterior = (BasicDBObject) MongoInterface.getInstance().getAdvice(currentId).get(parts[3]);
    procesaImagen(parametros, anterior);
    MongoInterface.getInstance().savePlainData(currentId, parts[3], parametros);
    if (fileflag) {
        throw aex;
    }
}

From source file:net.morphbank.mbsvc3.webservices.RestServiceExcelUpload.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ArrayList<String> reportContent = new ArrayList<String>();
    response.setContentType("text/xml");
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);

    try {//w  w w .j a v  a2  s.c  o  m
        // Process the uploaded items
        List<?> /* FileItem */ items = upload.parseRequest(request);
        Iterator<?> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) {
                // processFormField(item);
            } else {
                String report = this.processUploadedFile(item);
                reportContent = this.outputReport(report, reportContent);
                htmlPresentation(request, response, folderPath, reportContent);
            }
        }
    } catch (FileUploadException e) {
        e.printStackTrace();
    }

}

From source file:it.swim.servlet.profilo.azioni.RilasciaFeedBackServlet.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)/*from www  .ja  va2 s  . c o  m*/
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // ottengo l'email dell'utente collegato dalla sessione, appoggiandomi
    // ad una classe di utilita'
    String emailUtenteCollegato = (String) UtenteCollegatoUtil.getEmailUtenteCollegato(request);
    List<FileItem> items;
    int punteggioFeedBack = 0;
    String commento = "";
    // se e' null e' perche' l'utente non e' collegato e allora devo fare il
    // redirect alla home

    if (emailUtenteCollegato == null) {
        response.sendRedirect("../../home");
        return;
    }

    try {
        items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        for (FileItem item : items) {
            if (item.isFormField()) {
                // Process regular form field (input
                // type="text|radio|checkbox|etc", select, etc).
                // ... (do your job here)
                if (item.getFieldName().equals("punteggioFeedBack")) {
                    punteggioFeedBack = Integer.parseInt(item.getString().trim());
                }
                if (item.getFieldName().equals("commentoFeedBack")) {
                    commento = item.getString().trim();
                }
            }
        }
    } catch (FileUploadException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    if (punteggioFeedBack < 1 || punteggioFeedBack > 5) {
        request.setAttribute("erroreNelPunteggio", "Il punteggio deve essere compreso tra 1 e 5");
        getServletConfig().getServletContext().getRequestDispatcher("/jsp/utenti/profilo/rilascioFeedBack.jsp")
                .forward(request, response);
        return;
    }
    if (commento.isEmpty()) {
        commento = "Non ci sono commenti rilasciati";
    }
    try {
        collab.rilasciaFeedback(idCollaborazione, punteggioFeedBack, commento);
    } catch (LoginException e) {
        // TODO Auto-generated catch block
        request.setAttribute("erroreNelPunteggio", "Collaborazione a cui aggiungere il feedBack non trovata");
        getServletConfig().getServletContext().getRequestDispatcher("/jsp/utenti/profilo/rilascioFeedBack.jsp")
                .forward(request, response);
        return;
    }
    request.setAttribute("feedBackRilasciato", "Feedback rilasciato con successo");
    getServletConfig().getServletContext().getRequestDispatcher("/jsp/utenti/profilo/rilascioFeedBack.jsp")
            .forward(request, response);

}

From source file:com.Uploader.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new ServletException("Content type is not multipart/form-data");
    }/*from   w  w  w. ja  v a2 s .  c  om*/

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.write("<html><head></head><body>");
    try {
        List<FileItem> fileItemsList = uploader.parseRequest(request);
        Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
        while (fileItemsIterator.hasNext()) {
            FileItem fileItem = fileItemsIterator.next();
            System.out.println("FieldName=" + fileItem.getFieldName());
            System.out.println("FileName=" + fileItem.getName());
            System.out.println("ContentType=" + fileItem.getContentType());
            System.out.println("Size in bytes=" + fileItem.getSize());
            File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator
                    + fileItem.getName());
            System.out.println("Absolute Path at server=" + file.getAbsolutePath());
            fileItem.write(file);
            out.write("File " + fileItem.getName() + " uploaded successfully.");
            out.write("<br>");
            out.write("<a href=\"Uploader?fileName=" + fileItem.getName() + "\">Download " + fileItem.getName()
                    + "</a>");
        }
    } catch (FileUploadException e) {
        out.write("Exception in uploading file.");
        e.printStackTrace();
    } catch (Exception e) {
        out.write("Exception in uploading file.");
        e.printStackTrace();
    }
    out.write("</body></html>");
}