Example usage for org.apache.commons.fileupload.disk DiskFileItemFactory DiskFileItemFactory

List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory DiskFileItemFactory

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.disk DiskFileItemFactory DiskFileItemFactory.

Prototype

public DiskFileItemFactory() 

Source Link

Document

Constructs an unconfigured instance of this class.

Usage

From source file:emsa.webcoc.cleanup.servlet.UploadServet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  ww  w .ja  va 2  s .  c o m
 *
 * @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 {

    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    if (!isMultipart) {
        out.println("<html>");
        out.println("<head>");
        out.println("<title>XML file clean up</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<p>No file uploaded</p>");
        out.println("</body>");
        out.println("</html>");
        return;
    }

    DiskFileItemFactory factory = new DiskFileItemFactory();

    //Maximum size that will be stored into memory
    factory.setSizeThreshold(MAXMEMSIZE);
    //Path to save file if its size is bigger than MAXMEMSIZE
    factory.setRepository(new File(REPOSITORY));
    ServletFileUpload upload = new ServletFileUpload(factory);

    out.println("<html>");
    out.println("<head>");
    out.println("<title>XML file clean up</title>");
    out.println("</head>");
    out.println("<body>");

    try {
        List<FileItem> fileItems = upload.parseRequest(request);
        Iterator<FileItem> t = fileItems.iterator();

        while (t.hasNext()) {
            FileItem f = t.next();

            if (!f.isFormField()) {
                if (f.getContentType().equals("text/xml")) { //Check weather or not the uploaded file is an XML file

                    String uniqueFileName = f.getName() + "-" + request.getSession().getId() + ".xml"; //Creates unique name
                    String location = (String) this.getServletContext().getAttribute("newFileLocation");

                    CoCCleanUp clean = new CoCCleanUp(uniqueFileName, location);

                    if (clean.cleanDocument(f.getInputStream()) == 0) {
                        out.println("<h3>" + f.getName() + " was clean</h3>");
                        out.println(clean.printHTMLStatistics());
                        out.println("<br /><form action='download?filename=" + uniqueFileName
                                + "' method='post'><input type='submit' value='Download'/></form></body></html>");
                    } else {
                        out.println("<h3>" + clean.getErrorMessage() + "</h3>");
                        out.println(
                                "<br /><form action='index.html' method='post'><input type='submit' value='Go Back'/></form></body></html>");
                    }
                } else {
                    out.println("<h3>The file " + f.getName() + " is not an xml file</h3>");
                    out.println(
                            "<br /><form action='index.html' method='post'><input type='submit' value='Go Back'/></form></body></html>");
                    logger.warn("The file " + f.getName() + " is not an xml file: " + f.getContentType());
                }
            }
        }

        File repository = factory.getRepository();
        cleanTmpFiles(repository);

    } catch (IOException | FileUploadException e) {
        out.println("<h3>Something went wrong</h3></br>");
        out.println(
                "<br /><form action='index.html' method='post'><input type='submit' value='Go Back'/></form></body></html>");
    }
}

From source file:it.biblio.servlets.Inserimento_Ristampa.java

/**
 * metodo per gestire l'upload di file//from  ww w  .j a  v  a 2 s  . c om
 *
 * @param request
 * @param response
 * @param k
 * @return
 * @throws IOException
 */
private boolean upload(HttpServletRequest request) throws IOException, Exception {

    Map<String, Object> ristampe = new HashMap<String, Object>();
    int idopera = Integer.parseInt(request.getParameter("id"));

    if (ServletFileUpload.isMultipartContent(request)) {

        FileItemFactory fif = new DiskFileItemFactory();
        ServletFileUpload sfo = new ServletFileUpload(fif);
        List<FileItem> items = sfo.parseRequest(request);
        for (FileItem item : items) {
            String fname = item.getFieldName();
            if (item.isFormField() && fname.equals("ISBN") && !item.getString().isEmpty()) {
                ristampe.put("isbn", item.getString());
            } else if (item.isFormField() && fname.equals("numero_pagine") && !item.getString().isEmpty()) {
                ristampe.put("numpagine", Integer.parseInt(item.getString()));
            } else if (item.isFormField() && fname.equals("anno_pub") && !item.getString().isEmpty()) {
                ristampe.put("datapub", item.getString());
            } else if (item.isFormField() && fname.equals("editore") && !item.getString().isEmpty()) {
                ristampe.put("editore", item.getString());
            } else if (item.isFormField() && fname.equals("lingua") && !item.getString().isEmpty()) {
                ristampe.put("lingua", item.getString());
            } else if (item.isFormField() && fname.equals("indice") && !item.getString().isEmpty()) {
                ristampe.put("indice", item.getString());
                //se  stato inserito un pdf salvo il file e inserisco nella mappa i dati
            } else if (!item.isFormField() && fname.equals("PDF")) {
                String name = item.getName();
                long size = item.getSize();
                if (size > 0 && !name.isEmpty()) {
                    File target = new File(getServletContext().getRealPath("") + File.separatorChar + "PDF"
                            + File.separatorChar + name);
                    item.write(target);
                    ristampe.put("download", "PDF" + File.separatorChar + name);
                }
                //salvo l'immagine e inserisco i dati nella mappa
            } else if (!item.isFormField() && fname.equals("copertina")) {
                String name = item.getName();
                long size = item.getSize();
                if (size > 0 && !name.isEmpty()) {
                    File target = new File(getServletContext().getRealPath("") + File.separatorChar
                            + "Copertine" + File.separatorChar + name);
                    item.write(target);
                    ristampe.put("copertina", "Copertine" + File.separatorChar + name);
                }
            }
        }
        ristampe.put("pubblicazioni", idopera);
        return Database.insertRecord("ristampe", ristampe);

    }
    return false;
}

From source file:calliope.handler.put.AesePutHandler.java

private void parseRequest(HttpServletRequest request) throws AeseException {
    try {/*  w  w  w  .  j  a  v  a  2  s  .  c  o m*/
        FileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // Parse the request
        List items = upload.parseRequest(request);
        for (int i = 0; i < items.size(); i++) {
            FileItem item = (FileItem) items.get(i);
            if (item.isFormField()) {
                String fieldName = item.getFieldName();
                if (fieldName != null) {
                    String contents = item.getString();
                    if (fieldName.equals(Params.STRIPPER))
                        stripperName = contents;
                    else if (fieldName.equals(Params.ENCODING))
                        encoding = contents;
                    else if (fieldName.equals(Params.STYLE))
                        style = contents;
                    else if (fieldName.equals(Params.TITLE))
                        title = contents;
                    else if (fieldName.equals(Params.VERSION1))
                        version1 = contents;
                    else if (fieldName.equals(Params.AUTHOR))
                        author = contents;
                    else if (fieldName.equals(Params.DESCRIPTION))
                        description = contents;
                }
            } else if (item.getName().length() > 0) {
                byte[] rawData = item.get();
                guessEncoding(rawData);
                if (encoding == null)
                    encoding = guessEncoding(rawData);
                fileContent = new String(rawData, encoding);
            }
        }
    } catch (Exception e) {
        throw new AeseException(e);
    }
}

From source file:com.wakasta.tubes2.AddProductPost.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String item_data = "";
    // Check that we have a file upload request
    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    if (!isMultipart) {
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<p>No file uploaded</p>");
        out.println("</body>");
        out.println("</html>");
        return;//from   w ww.  j  a  v a2s . c o  m
    }
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    factory.setRepository(new File("c:\\temp"));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);

    try {
        // Parse the request to get file items.
        List fileItems = upload.parseRequest(request);

        // Process the uploaded file items
        Iterator i = fileItems.iterator();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();
                // Write the file
                if (fileName.lastIndexOf("\\") >= 0) {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                } else {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
                }

                item_data = Base64.encodeBase64String(fi.get());

                fi.write(file);

                //                    out.println("Uploaded Filename: " + fileName + "<br>");
                //                    out.println(file);
            }
        }
        out.println("</body>");
        out.println("</html>");
    } catch (FileUploadException ex) {
        Logger.getLogger(AddProductPost.class.getName()).log(Level.SEVERE, null, ex);
    } catch (java.lang.Exception ex) {
        Logger.getLogger(AddProductPost.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:admin.controller.ServletEditCategories.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* w  w  w . ja va 2  s .  co  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {

        upload_path = AppConstants.ORG_CATEGORIES_HOME;

        // Verify the content type
        String contentType = request.getContentType();
        if ((contentType.indexOf("multipart/form-data") >= 0)) {

            DiskFileItemFactory factory = new DiskFileItemFactory();
            // maximum size that will be stored in memory
            factory.setSizeThreshold(maxMemSize);
            // Location to save data that is larger than maxMemSize.
            factory.setRepository(new File(AppConstants.TMP_FOLDER));

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // maximum file size to be uploaded.
            upload.setSizeMax(maxFileSize);

            // Parse the request to get file items.
            List fileItems = upload.parseRequest(request);

            // Process the uploaded file items
            Iterator i = fileItems.iterator();

            out.println("<html>");
            out.println("<head>");
            out.println("<title>JSP File upload</title>");
            out.println("</head>");
            out.println("<body>");
            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (fi.isFormField()) {
                    // Get the uploaded file parameters
                    field_name = fi.getFieldName();
                    if (field_name.equals("category_name")) {
                        category_name = fi.getString();
                    }
                    if (field_name.equals("category_id")) {
                        category_id = fi.getString();
                    }
                    if (field_name.equals("organization")) {
                        organization_id = fi.getString();
                        upload_path = upload_path + File.separator + organization_id;
                    }

                } else {
                    field_name = fi.getFieldName();
                    file_name = fi.getName();

                    if (file_name != "") {
                        File uploadDir = new File(upload_path);
                        if (!uploadDir.exists()) {
                            uploadDir.mkdirs();
                        }

                        //                            int inStr = file_name.indexOf(".");
                        //                            String Str = file_name.substring(0, inStr);
                        //
                        //                            file_name = category_name + "_" + Str + ".jpeg";
                        file_name = category_name + "_" + file_name;
                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();

                        String filePath = upload_path + File.separator + file_name;
                        File storeFile = new File(filePath);

                        fi.write(storeFile);

                        out.println("Uploaded Filename: " + filePath + "<br>");
                    }
                }
            }
            categories.editCategories(Integer.parseInt(category_id), Integer.parseInt(organization_id),
                    category_name, file_name);
            response.sendRedirect(request.getContextPath() + "/admin/categories.jsp");
            out.println("</body>");
            out.println("</html>");
        } else {
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet upload</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<p>No file uploaded</p>");
            out.println("</body>");
            out.println("</html>");
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Exception while editing categories", ex);
    } finally {
        try {
            out.close();
        } catch (Exception e) {
        }
    }

}

From source file:admin.controller.ServletUploadFonts.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w w w  . j  a v a2  s .c o m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);
    response.setContentType("text/html;charset=UTF-8");
    String filePath;
    String file_name = null, field_name, upload_path;
    RequestDispatcher request_dispatcher;
    String font_name = "", look_id;
    String font_family_name = "";
    PrintWriter out = response.getWriter();
    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;

    try {

        // Verify the content type
        String contentType = request.getContentType();
        if ((contentType.indexOf("multipart/form-data") >= 0)) {

            DiskFileItemFactory factory = new DiskFileItemFactory();
            // maximum size that will be stored in memory
            factory.setSizeThreshold(maxMemSize);
            // Location to save data that is larger than maxMemSize.
            factory.setRepository(new File(AppConstants.TMP_FOLDER));

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // maximum file size to be uploaded.
            upload.setSizeMax(maxFileSize);

            // Parse the request to get file items.
            List fileItems = upload.parseRequest(request);

            // Process the uploaded file items
            Iterator i = fileItems.iterator();

            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (fi.isFormField()) {
                    // Get the uploaded file parameters
                    field_name = fi.getFieldName();
                    if (field_name.equals("fontname")) {
                        font_name = fi.getString();
                    }
                    if (field_name.equals("fontstylecss")) {
                        font_family_name = fi.getString();
                    }

                } else {

                    //                        check = fonts.checkAvailability(font_name);
                    //                        if (check == false){

                    field_name = fi.getFieldName();
                    file_name = fi.getName();

                    if (file_name != "") {
                        File uploadDir = new File(AppConstants.BASE_FONT_UPLOAD_PATH);
                        if (!uploadDir.exists()) {
                            uploadDir.mkdirs();
                        }

                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();

                        filePath = AppConstants.BASE_FONT_UPLOAD_PATH + File.separator + file_name;
                        File storeFile = new File(filePath);

                        fi.write(storeFile);

                        out.println("Uploaded Filename: " + filePath + "<br>");
                    }
                    fonts.addFont(font_name, file_name, font_family_name);
                    response.sendRedirect(request.getContextPath() + "/admin/fontsfamily.jsp");

                    //                            }else {
                    //                                response.sendRedirect(request.getContextPath() + "/admin/fontsfamily.jsp?exist=exist");
                    //                            }
                }
            }
        }

    } catch (Exception e) {
        logger.log(Level.SEVERE, "Exception while uploading fonts", e);
    }
}

From source file:com.javaweb.controller.ThemTinTucServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request//  w  w w .ja  v a2s .  c  o m
 * @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, ParseException {
    response.setContentType("text/html;charset=UTF-8");
    request.setCharacterEncoding("UTF-8");

    //response.setCharacterEncoding("UTF-8");
    HttpSession session = request.getSession();
    //        session.removeAttribute("errorreg");
    String TieuDe = "", NoiDung = "", ngaydang = "", GhiChu = "", fileName = "";
    int idloaitin = 0, idTK = 0;

    TintucService tintucservice = new TintucService();

    //File upload
    String folderupload = getServletContext().getInitParameter("file-upload");
    String rootPath = getServletContext().getRealPath("/");
    filePath = rootPath + folderupload;
    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();

    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    factory.setRepository(new File("C:\\Windows\\Temp\\"));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);

    try {
        // Parse the request to get file items.
        List fileItems = upload.parseRequest(request);

        // Process the uploaded file items
        Iterator i = fileItems.iterator();

        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters

                String fieldName = fi.getFieldName();
                fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();

                //change file name
                fileName = FileService.ChangeFileName(fileName);

                // Write the file
                if (fileName.lastIndexOf("\\") >= 0) {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                } else {
                    file = new File(filePath + "/" + fileName.substring(fileName.lastIndexOf("\\") + 1));
                }
                fi.write(file);
                //                    out.println("Uploaded Filename: " + fileName + "<br>");
            }

            if (fi.isFormField()) {
                if (fi.getFieldName().equalsIgnoreCase("TieuDe")) {
                    TieuDe = fi.getString("UTF-8");
                } else if (fi.getFieldName().equalsIgnoreCase("NoiDung")) {
                    NoiDung = fi.getString("UTF-8");
                } else if (fi.getFieldName().equalsIgnoreCase("NgayDang")) {
                    ngaydang = fi.getString("UTF-8");
                } else if (fi.getFieldName().equalsIgnoreCase("GhiChu")) {
                    GhiChu = fi.getString("UTF-8");
                } else if (fi.getFieldName().equalsIgnoreCase("loaitin")) {
                    idloaitin = Integer.parseInt(fi.getString("UTF-8"));
                } else if (fi.getFieldName().equalsIgnoreCase("idtaikhoan")) {
                    idTK = Integer.parseInt(fi.getString("UTF-8"));
                }
            }
        }

    } catch (Exception ex) {
        System.out.println(ex);
    }

    Date NgayDang = new SimpleDateFormat("yyyy-MM-dd").parse(ngaydang);
    Tintuc tintuc = new Tintuc(idloaitin, idTK, fileName, TieuDe, NoiDung, NgayDang, GhiChu);

    boolean rs = tintucservice.InsertTintuc(tintuc);
    if (rs) {
        session.setAttribute("kiemtra", "1");
        String url = "ThemTinTuc.jsp";
        response.sendRedirect(url);
    } else {
        session.setAttribute("kiemtra", "0");
        String url = "ThemTinTuc.jsp";
        response.sendRedirect(url);
    }

    //        try (PrintWriter out = response.getWriter()) {
    //            /* TODO output your page here. You may use following sample code. */
    //            out.println("<!DOCTYPE html>");
    //            out.println("<html>");
    //            out.println("<head>");
    //            out.println("<title>Servlet ThemTinTucServlet</title>");            
    //            out.println("</head>");
    //            out.println("<body>");
    //            out.println("<h1>Servlet ThemTinTucServlet at " + request.getContextPath() + "</h1>");
    //            out.println("</body>");
    //            out.println("</html>");
    //        }
}

From source file:com.siberhus.web.ckeditor.servlet.MultipartServletRequest.java

public MultipartServletRequest(HttpServletRequest request) throws FileUploadException {
    super(request);

    //      if(!"POST".equals(request.getMethod())){
    //         return;
    //      }/*from   ww  w  . j  ava  2 s.c  o  m*/
    CkeditorConfig config = CkeditorConfigurationHolder.config();
    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // Set factory constraints
    if (config.fileupload().sizeThreshold() != null) {
        factory.setSizeThreshold(config.fileupload().sizeThreshold());
    }
    if (config.fileupload().repository() != null) {
        factory.setRepository(config.fileupload().repository());
    }

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    // Set overall request size constraint
    if (config.fileupload().sizeMax() != null) {
        upload.setSizeMax(config.fileupload().sizeMax());
    }
    if (config.fileupload().fileSizeMax() != null) {
        upload.setFileSizeMax(config.fileupload().fileSizeMax());
    }
    // Copy params from query string
    Enumeration<String> paramNames = request.getParameterNames();
    while (paramNames.hasMoreElements()) {
        String paramName = paramNames.nextElement();
        String paramValues[] = request.getParameterValues(paramName);
        if (paramValues != null) {
            this.paramMap.put(paramName, Literal.list(paramValues));
        }
    }

    @SuppressWarnings("unchecked")
    List<FileItem> itemList = upload.parseRequest(request);

    for (FileItem item : itemList) {
        String fieldName = item.getFieldName();
        if (item.isFormField()) {
            List<String> values = paramMap.get(fieldName);
            if (values == null) {
                paramMap.put(fieldName, Literal.list(item.getString()));
            } else {
                values.add(item.getString());
            }
        } else {
            fileItemMap.put(fieldName, item);
            fileItems.add(item);
        }
    }
}

From source file:de.fau.amos.FileUpload.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String pathInfo = request.getPathInfo();
    System.out.println("called fileupload: " + pathInfo);
    boolean isImportProductionData = pathInfo != null && pathInfo.startsWith("/importProductionData");
    boolean isImportEnergyData = pathInfo != null && pathInfo.startsWith("/importEnergyData");

    if (ServletFileUpload.isMultipartContent(request)) {
        try {/*  ww w.ja  va 2 s . c om*/
            List<FileItem> list = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            for (FileItem fi : list) {
                if (!fi.isFormField()) {
                    String rand = "";
                    for (int i = 0; i < 6; i++) {
                        rand += (int) (Math.random() * 10);
                    }
                    String plantId = "";
                    if (isImportEnergyData || isImportProductionData) {
                        plantId = request.getPathInfo().replace((isImportEnergyData ? "/importEnergyData"
                                : (isImportProductionData ? "/importProductionData" : "")), "");
                    }
                    if (plantId == null || plantId.length() == 0) {
                        plantId = "";
                        //                  }else{
                        //                     plantId="_"+plantId;
                    }
                    String name = new File(rand + "_" + fi.getName()).getName()
                            + (isImportEnergyData ? "_impED" + plantId
                                    : (isImportProductionData ? "_impPD" + plantId : ""));

                    File folder = null;
                    if (isImportEnergyData || isImportProductionData) {
                        folder = new File(System.getProperty("userdir.location"), "import");
                    } else {
                        folder = new File(System.getProperty("userdir.location"), "uploads");
                    }
                    if (!folder.exists()) {
                        folder.mkdirs();
                    }
                    fi.write(new File(folder, name));
                }
            }

            request.setAttribute("message", "File uploaded successfully");
        } catch (Exception e) {
            request.setAttribute("errorMessage", "File upload failed!");
        }

    } else {
        request.setAttribute("errorMessage", "Something went wrong.");
    }

    if (isImportEnergyData || isImportProductionData) {
        //         request.setAttribute("plant",request.getPathInfo().replace("/import",""));
        //         request.getRequestDispatcher("/intern/import.jsp").forward(request, response);
        response.sendRedirect(request.getContextPath() + "/intern/import.jsp");
    } else {
        response.sendRedirect(request.getContextPath() + "/intern/funktion3.jsp");
    }

}

From source file:dk.netarkivet.harvester.webinterface.TrapCreateOrUpdateAction.java

@Override
protected void doAction(PageContext context, I18n i18n) {
    String name = null;//from w ww  .j a  v  a  2 s  . com
    boolean isActive = true;
    String description = null;
    InputStream is = null;
    String id = null;
    String fileName = null;
    HttpServletRequest request = (HttpServletRequest) context.getRequest();
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<FileItem> items = null;
    try {
        items = upload.parseRequest(request);
    } catch (FileUploadException e) {
        HTMLUtils.forwardWithErrorMessage(context, i18n, e, "errormsg;crawlertrap.upload.error");
        throw new ForwardedToErrorPage("Error on multipart post", e);
    }
    for (FileItem item : items) {
        if (item.isFormField()) {
            if (item.getFieldName().equals(Constants.TRAP_NAME)) {
                name = item.getString();
            } else if (item.getFieldName().equals(Constants.TRAP_IS_ACTIVE)) {
                isActive = Boolean.parseBoolean(item.getString());
            } else if (item.getFieldName().equals(Constants.TRAP_DESCRIPTION)) {
                description = item.getString();
            } else if (item.getFieldName().equals(Constants.TRAP_ID)) {
                id = item.getString();
            }
        } else {
            try {
                fileName = item.getName();
                is = item.getInputStream();
            } catch (IOException e) {
                HTMLUtils.forwardWithErrorMessage(context, i18n, e, "errormsg;crawlertrap.upload.error");
                throw new ForwardedToErrorPage("Error on multipart post", e);
            }
        }
    }
    GlobalCrawlerTrapListDAO dao = GlobalCrawlerTrapListDBDAO.getInstance();
    if (id != null) { // update existing trap list
        int trapId = Integer.parseInt(id);
        GlobalCrawlerTrapList trap = dao.read(trapId);
        trap.setActive(isActive);
        trap.setDescription(description);
        trap.setName(name);
        if (fileName != null && !fileName.isEmpty()) {
            log.debug("Reading global crawler trap list from '" + fileName + "'");
            try {
                trap.setTrapsFromInputStream(is, name);
            } catch (ArgumentNotValid argumentNotValid) {
                HTMLUtils.forwardWithErrorMessage(context, i18n, "errormsg;crawlertrap.regexp.error");
                throw new ForwardedToErrorPage(argumentNotValid.getMessage());
            }
        }
        dao.update(trap);
    } else { // create new trap list
        log.debug("Reading global crawler trap list from '" + fileName + "'");
        GlobalCrawlerTrapList trap = new GlobalCrawlerTrapList(is, name, description, isActive);
        if (!dao.exists(name)) {
            dao.create(trap);
        } else {
            // crawlertrap named like this already exists.
            HTMLUtils.forwardWithErrorMessage(context, i18n, "errormsg;crawlertrap.0.exists.error", name);
            throw new ForwardedToErrorPage("Crawlertrap with name '" + name + "' exists already");
        }
    }
}