Example usage for org.apache.commons.fileupload.servlet ServletFileUpload ServletFileUpload

List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload ServletFileUpload

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.servlet ServletFileUpload ServletFileUpload.

Prototype

public ServletFileUpload(FileItemFactory fileItemFactory) 

Source Link

Document

Constructs an instance of this class which uses the supplied factory to create FileItem instances.

Usage

From source file:fi.vm.sade.organisaatio.resource.TempFileResource.java

@POST
@Path("/")
@Produces(MediaType.TEXT_PLAIN)//www  .j  a  va 2 s.co  m
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Secured({ "ROLE_APP_ORGANISAATIOHALLINTA" })
public String addImage(@Context HttpServletRequest request, @Context HttpServletResponse response) {
    LOG.info("Adding attachment " + request.getMethod());
    Map<String, String> result = null;

    try {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            for (FileItem item : upload.parseRequest(request)) {
                if (item.getName() != null) {
                    result = storeAttachment(item);
                }
            }
        } else {
            response.setStatus(400);
            response.getWriter().append("Not a multipart request");
        }
        LOG.info("Added attachment: " + result);
        JSONObject json = new JSONObject(result);
        return json.toString();
    } catch (Exception e) {
        return "organisaatio.fileupload.error";
    }
}

From source file:controller.ControlPembayaran.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String timeStamp = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss").format(Calendar.getInstance().getTime());
    String timeStamp2 = new SimpleDateFormat("yyyyMMdd").format(Calendar.getInstance().getTime());

    Pembayaran p = new Pembayaran();
    DatabaseManager db = new DatabaseManager();

    //Menyimpan file ke dalam sistem
    File file;/*from   ww  w  . ja  v  a 2 s.  c o  m*/
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    String filePath = "c:/Apache/";

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

        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(maxMemSize);
        factory.setRepository(new File("c:\\temp"));
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(maxFileSize);
        try {
            List fileItems = upload.parseRequest(request);
            Iterator i = fileItems.iterator();

            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (!fi.isFormField()) {
                    if (fi.getName().contains(".csv")) {
                        String fieldName = fi.getFieldName();
                        String fileName = fi.getName();
                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();
                        file = new File(filePath + "DataPembayaran_" + timeStamp + ".csv");
                        fi.write(file);
                    } else {
                        throw new Exception("Format File Salah");
                    }
                }
            }
        } catch (Exception ex) {
            returnError(request, response, ex);
        }
    } else {
        Exception e = new Exception("no file uploaded");
        returnError(request, response, e);
    }
    //Membaca file dari dalam sistem
    String csvFile = filePath + "DataPembayaran_" + timeStamp + ".csv";
    BufferedReader br = null;
    String line = "";
    String cvsSplitBy = ",";

    try {
        br = new BufferedReader(new FileReader(csvFile));
        int counter = 1;
        while ((line = br.readLine()) != null) {

            // use comma as separator
            String[] dataSet = line.split(cvsSplitBy);
            p.setID(timeStamp2 + "_" + counter);
            p.setWaktuPembayaran(dataSet[0]);
            p.setNoRekening(dataSet[1]);
            p.setJumlahPembayaran(Double.parseDouble(dataSet[2]));
            p.setNis(dataSet[3].substring(0, 5));
            p.setBulanTagihan(Integer.parseInt(dataSet[3].substring(6)));
            //Membandingkan nis, jumlah, bulan pembayaran ke tagihan
            Tagihan[] t = Tagihan.getListTagihan(p.getNis());
            for (int i = 0; i < t.length; i++) {
                if (t[i].getNis().equals(p.getNis()) && t[i].getJumlah_pembayaran() == p.getJumlahPembayaran()
                        && t[i].getBulan_tagihan() == p.getBulanTagihan())// bandingkan jumlah pembayaran
                {
                    //Masukan data pembayaran ke database
                    Pembayaran.simpanPembayaran(p);
                    //update status pembayaran tagihan
                    t[i].verifikasiSukses(p.getNis(), p.getBulanTagihan());//update status bayar tagihan menjadi sudah bayar
                }
            }
            counter++;
        }
        this.tampil(request, response, "Data Terverifikasi");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //        }
}

From source file:edu.lafayette.metadb.web.controlledvocab.UpdateVocab.java

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*//*from www . j av a2  s.  c  om*/
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // TODO Auto-generated method stub
    PrintWriter out = response.getWriter();
    String vocabName = null;
    String name = "nothing";
    String status = "Upload failed ";

    try {

        if (ServletFileUpload.isMultipartContent(request)) {
            status = "isMultiPart";
            ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
            List fileItemsList = servletFileUpload.parseRequest(request);
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            diskFileItemFactory.setSizeThreshold(40960); /* the unit is bytes */

            InputStream input = null;
            Iterator it = fileItemsList.iterator();
            String result = "";
            String vocabs = null;
            int assigned = -1;

            while (it.hasNext()) {
                FileItem fileItem = (FileItem) it.next();
                result += "UpdateVocab: Form Field: " + fileItem.isFormField() + " Field name: "
                        + fileItem.getFieldName() + " Name: " + fileItem.getName() + " String: "
                        + fileItem.getString("utf-8") + "\n";
                if (fileItem.isFormField()) {
                    /* The file item contains a simple name-value pair of a form field */
                    if (fileItem.getFieldName().equals("vocab-name"))
                        vocabName = fileItem.getString();
                    else if (fileItem.getFieldName().equals("vocab-terms"))
                        vocabs = fileItem.getString("utf-8");
                    else if (fileItem.getFieldName().equals("assigned-field"))
                        assigned = Integer.parseInt(fileItem.getString());
                } else {
                    if (fileItem.getString() != null && !fileItem.getString().equals("")) {
                        @SuppressWarnings("unused")
                        String content = "nothing";
                        /* The file item contains an uploaded file */

                        /* Create new File object
                        File uploadedFile = new File("test.txt");
                        if(!uploadedFile.exists())
                           uploadedFile.createNewFile();
                        // Write the uploaded file to the system
                        fileItem.write(uploadedFile);
                        */
                        name = fileItem.getName();
                        content = fileItem.getContentType();
                        input = fileItem.getInputStream();
                    }
                }
            }
            //MetaDbHelper.note(result);
            if (vocabName != null) {
                Set<String> vocabList = new TreeSet<String>();
                if (input != null) {
                    Scanner fileSc = new Scanner(input);
                    while (fileSc.hasNextLine()) {
                        String vocabEntry = fileSc.nextLine();
                        vocabList.add(vocabEntry.trim());
                    }

                    HttpSession session = request.getSession(false);
                    if (session != null) {
                        String userName = (String) session.getAttribute("username");
                        SysLogDAO.log(userName, Global.SYSLOG_PROJECT,
                                "User " + userName + " created vocab " + vocabName);
                    }
                    status = "Vocab name: " + vocabName + ". File name: " + name + "\n";

                } else {
                    //MetaDbHelper.note(vocabs);
                    for (String vocabTerm : vocabs.split("\n"))
                        vocabList.add(vocabTerm);
                }
                if (!vocabList.isEmpty()) {
                    boolean updated = ControlledVocabDAO.addControlledVocab(vocabName, vocabList)
                            || ControlledVocabDAO.updateControlledVocab(vocabName, vocabList);
                    if (updated) {
                        status = "Vocab " + vocabName + " updated successfully ";
                        if (assigned != -1)
                            if (!AdminDescAttributesDAO.setControlledVocab(assigned, vocabName)) {
                                status = "Vocab " + vocabName + " cannot be assigned to " + assigned;
                            }

                    } else
                        status = "Vocab " + vocabName + " cannot be updated/created";
                } else
                    status = "Vocab " + vocabName + " has empty vocabList";
            }
        }
    } catch (Exception e) {
        MetaDbHelper.logEvent(e);
    }
    MetaDbHelper.note(status);
    out.print(status);
    out.flush();
}

From source file:Control.HandleAddRestaurant.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  w w  w . j a  v a2s .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, FileUploadException, Exception {
    response.setContentType("text/html;charset=UTF-8");
    HttpSession session = request.getSession();
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        String path = getClass().getResource("/").getPath();
        String[] tempS = null;
        if (Paths.path == null) {
            File file = new File(path + "test.html");
            path = file.getParent();
            File file1 = new File(path + "test1.html");
            path = file1.getParent();
            File file2 = new File(path + "test1.html");
            path = file2.getParent();
            Paths.path = path;
        } else {
            path = Paths.path;
        }
        path = Paths.tempPath;
        Restaurant temp = new Restaurant();
        String name = null;
        String sepName = Tools.CurrentTime();
        if (ServletFileUpload.isMultipartContent(request)) {
            List<?> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
            Iterator iter = multiparts.iterator();
            int index = 0;
            tempS = new String[multiparts.size() - 1];
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (!item.isFormField()) {
                    name = new File(item.getName()).getName();

                    String FilePath = path + Paths.logoPathStore + sepName + name;
                    item.write(new File(FilePath));
                } else {
                    String test = item.getFieldName();
                    tempS[index++] = item.getString();
                }
            }
            index = 0;
            temp.ID = tempS[index++];
            temp.name = tempS[index++];
            temp.address = tempS[index++];
            temp.city = tempS[index++];
            temp.state = tempS[index++];
            temp.zipcode = tempS[index++];
            temp.email = tempS[index++];
            temp.phone = tempS[index++];
            temp.monHours = tempS[index++];
            temp.sunHours = tempS[index++];
            temp.minPrice = Double.parseDouble(tempS[index++]);
            temp.fee = Double.parseDouble(tempS[index++]);
            temp.type = Integer.parseInt(tempS[index++]);
            temp.logoImage = Paths.logoPath + sepName + name;
        }

        if (Restaurant.checkExisted(temp.ID, temp.name)) {

            response.sendRedirect("./Admin/AddRestaurant.jsp?index=1");
        } else {
            if (Restaurant.addNewRestaurant(temp)) {
                Tools.updateRestaurants(session);
                response.sendRedirect("./Admin/AddRestaurant.jsp?index=2");
            } else {
                response.sendRedirect("./Admin/AddRestaurant.jsp?index=3");
            }
        }

    } catch (Exception e) {
        response.sendRedirect("./Admin/AddRestaurant.jsp?index=0");
    }
}

From source file:mml.handler.post.MMLPostHandler.java

/**
 * Parse the import params from the request
 * @param request the http request//  w ww. j av a2  s .c om
 */
void parseImportParams(HttpServletRequest request) throws MMLException {
    try {
        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(this.encoding);
                    if (fieldName.equals(Params.DOCID)) {
                        int index = contents.lastIndexOf(".");
                        if (index != -1)
                            contents = contents.substring(0, index);
                        docid = contents;
                    } else if (fieldName.equals(Params.AUTHOR))
                        this.author = contents;
                    else if (fieldName.equals(Params.TITLE))
                        this.title = contents;
                    else if (fieldName.equals(Params.STYLE))
                        this.style = contents;
                    else if (fieldName.equals(Params.FORMAT))
                        this.format = contents;
                    else if (fieldName.equals(Params.SECTION))
                        this.section = contents;
                    else if (fieldName.equals(Params.VERSION1))
                        this.version1 = contents;
                    else if (fieldName.equals(Params.ENCODING))
                        encoding = contents;
                    else if (fieldName.equals(Params.ANNOTATIONS))
                        annotations = (JSONArray) JSONValue.parse(contents);
                }
            } else if (item.getName().length() > 0) {
                try {
                    // item.getName retrieves the ORIGINAL file name
                    String type = item.getContentType();
                    if (type != null) {
                        if (type.startsWith("image/")) {
                            InputStream is = item.getInputStream();
                            ByteHolder bh = new ByteHolder();
                            while (is.available() > 0) {
                                byte[] b = new byte[is.available()];
                                is.read(b);
                                bh.append(b);
                            }
                            ImageFile iFile = new ImageFile(item.getName(), item.getContentType(),
                                    bh.getData());
                            if (images == null)
                                images = new ArrayList<ImageFile>();
                            images.add(iFile);
                        } else if (type.equals("text/plain")) {
                            InputStream is = item.getInputStream();
                            ByteHolder bh = new ByteHolder();
                            while (is.available() > 0) {
                                byte[] b = new byte[is.available()];
                                is.read(b);
                                bh.append(b);
                            }
                            String style = new String(bh.getData(), encoding);
                            if (files == null)
                                files = new ArrayList<String>();
                            files.add(style);
                        }
                    }
                } catch (Exception e) {
                    throw new MMLException(e);
                }
            }
        }
    } catch (Exception e) {
        throw new MMLException(e);
    }
}

From source file:com.insurance.manage.UploadFile.java

private void uploadLicense(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //      boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    //       Create a factory for disk-based file items
    String custId = null;/*w w w  .j av  a 2 s .  com*/
    String year = null;
    String license = null;
    CustomerManager cManage = new CustomerManager();
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(1 * 1024 * 1024); //1 MB
    factory.setRepository(new File("temp"));

    //       Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    HttpSession session = request.getSession();
    //      System.out.println("eCust : "+session.getAttribute("eCust"));
    //      if (session.getAttribute("eCust")!=null) {
    //         Customer cEntity = (Customer)request.getAttribute("eCust");
    //         System.out.println("CustId : "+cEntity.getName());
    //      }

    //       Parse the request
    //      System.out.println("--------- Uploading --------------");
    try {
        List /* FileItem */ items = upload.parseRequest(request);
        //          Process the uploaded items
        Iterator iter = items.iterator();
        File fi = null;
        File file = null;
        Calendar calendar = Calendar.getInstance();
        DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = df.format(calendar.getTime()) + ".jpg";
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (item.isFormField()) {
                //                System.out.println(item.getFieldName()+" : "+item.getName()+" : "+item.getString()+" : "+item.getContentType());
                if (item.getFieldName().equals("custId") && !item.getString().equals("")) {
                    custId = item.getString();
                    //                   System.out.println("custId : "+custId);
                }
                if (item.getFieldName().equals("year") && !item.getString().equals("")) {
                    year = item.getString();
                    //                   System.out.println("year : "+year);
                }
                if (item.getFieldName().equals("license") && !item.getString().equals("")) {
                    license = (String) session.getAttribute(item.getString());
                    //                   System.out.println("license : "+license+" : "+session.getAttribute(item.getString()));
                }
            } else {
                //                Handle Uploaded files.
                //                System.out.println("Handle Uploaded files.");
                if (item.getFieldName().equals("vat") && !item.getName().equals("")) {
                    fi = new File(item.getName());
                    File uploadedFile = new File(
                            getServletContext().getRealPath("/images/license/vat/" + year + fileName));
                    item.write(uploadedFile);
                    cManage.updatePicture(custId, year, license, "vatpic", year + fileName);
                }
                if (item.getFieldName().equals("car") && !item.getName().equals("")) {
                    fi = new File(item.getName());
                    File uploadedFile = new File(
                            getServletContext().getRealPath("/images/license/car/" + year + fileName));
                    item.write(uploadedFile);
                    cManage.updatePicture(custId, year, license, "carpic", year + fileName);
                }
                if (item.getFieldName().equals("act") && !item.getName().equals("")) {
                    fi = new File(item.getName());
                    File uploadedFile = new File(
                            getServletContext().getRealPath("/images/license/act/" + year + fileName));
                    item.write(uploadedFile);
                    cManage.updatePicture(custId, year, license, "actpic", year + fileName);
                }
                if (item.getFieldName().equals("chk") && !item.getName().equals("")) {
                    fi = new File(item.getName());
                    File uploadedFile = new File(
                            getServletContext().getRealPath("/images/license/chk/" + year + fileName));
                    item.write(uploadedFile);
                    cManage.updatePicture(custId, year, license, "chkpic", year + fileName);
                }
            }
        }
    } catch (FileUploadException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    request.setAttribute("url", "setup/CustomerMultiMT.jsp?action=search&custId=" + custId);
    request.setAttribute("msg", "!!!Uploading !!!");
    getServletConfig().getServletContext().getRequestDispatcher("/Reload.jsp").forward(request, response);

}

From source file:controller.UpdateEC.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from www .  j ava2 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 {
    response.setContentType("text/html;charset=UTF-8");
    ExtenuatingCircumstance ec = new ExtenuatingCircumstance();
    if (ServletFileUpload.isMultipartContent(request)) {
        try {
            String fname = StringUtils.EMPTY;
            String title = StringUtils.EMPTY;
            String desciption = StringUtils.EMPTY;
            String status = StringUtils.EMPTY;
            int id = 0;
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
            ArrayList<FileItem> files = new ArrayList<>();
            for (FileItem item : multiparts) {
                if (item.isFormField()) {
                    if (item.getFieldName().equals("id")) {
                        id = Integer.parseInt(item.getString());
                        System.out.println("id: " + id);
                    }
                    if (item.getFieldName().equals("title")) {
                        title = item.getString();
                    }
                    if (item.getFieldName().equals("description")) {
                        desciption = item.getString();
                    }
                    if (item.getFieldName().equals("status")) {
                        status = item.getString();
                        System.out.println("status: " + status);
                    }

                } else {
                    if (StringUtils.isNotEmpty(item.getName())) {
                        files.add(item);
                    }
                }
            }

            HttpSession session = request.getSession(false);
            Account studentAccount = (Account) session.getAttribute("account");
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
            LocalDateTime now = LocalDateTime.now();

            // insert EC
            ec.setId(id);
            ec.setTitle(title);
            ec.setDescription(desciption);
            ec.setProcess_status(status);
            //ec.setSubmitted_date(now.toString());
            ec.setAccount(studentAccount.getId());

            new ExtenuatingCircumstanceDAO().updateEC(ec, "student");

            //insert additional evident evidence
            if (files.size() > 0) {
                insertedEvidence(files, now, ec, studentAccount);
            }

            request.setAttribute("resultMsg", "updated");
            request.getRequestDispatcher("AddNewECResult.jsp").forward(request, response);

        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        request.setAttribute("message", "Sorry this Servlet only handles file upload request");
    }
}

From source file:admin.controller.ServletAddLooks.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w w w.  j a  va2s.  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
 */
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    super.processRequest(request, response);
    String filePath;
    String fileName, fieldName;
    Looks look;
    RequestDispatcher request_dispatcher;
    String look_name = null;
    Integer organization_id = 0;
    boolean check;
    look = new Looks();
    check = false;

    response.setContentType("text/html;charset=UTF-8");
    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {
        String uploadPath = AppConstants.LOOK_IMAGES_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("/tmp"));

            // 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
                    fieldName = fi.getFieldName();
                    try {
                        if (fieldName.equals("lookname")) {
                            look_name = fi.getString();
                        }
                        if (fieldName.equals("organization")) {
                            organization_id = Integer.parseInt(fi.getString());
                        }
                    } catch (Exception e) {
                        logger.log(Level.SEVERE, "Exception while getting the look_name and organization_id",
                                e);
                    }
                } else {
                    check = look.checkAvailability(look_name, organization_id);

                    if (check == false) {
                        fieldName = fi.getFieldName();
                        fileName = fi.getName();

                        File uploadDir = new File(uploadPath);
                        if (!uploadDir.exists()) {
                            uploadDir.mkdirs();
                        }

                        //                            int inStr = fileName.indexOf(".");
                        //                            String Str = fileName.substring(0, inStr);
                        //
                        //                            fileName = look_name + "_" + Str + ".png";
                        fileName = look_name + "_" + fileName;
                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();

                        filePath = uploadPath + File.separator + fileName;
                        File storeFile = new File(filePath);

                        fi.write(storeFile);

                        look.addLooks(look_name, fileName, organization_id);
                        response.sendRedirect(request.getContextPath() + "/admin/looks.jsp");
                    } else {
                        response.sendRedirect(request.getContextPath() + "/admin/looks.jsp?exist=exist");
                    }

                }
            }

        } else {
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Exception while uploading the Looks image", ex);
    }
}

From source file:com.ci6225.marketzone.servlet.seller.AddProductServlet.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 * response)//  w ww.j  a  v a  2 s  .c o m
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String name = null;
    String description = null;
    String unitPrice = null;
    String quantity = null;
    FileItem imageItem = null;

    // constructs the folder where uploaded file will be stored
    //String uploadFolder = getServletContext().getRealPath("") + "/productImages";
    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(5000 * 1024);
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(5000 * 1024);

    try {
        // Parse the request
        List<FileItem> items = upload.parseRequest(request);
        Iterator iter = items.iterator();

        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (!item.isFormField()) {
                if (item.getFieldName().equals("productImage") && !item.getString().equals("")) {
                    imageItem = item;
                }
                System.out.println(item.getFieldName());
            } else {
                System.out.println(item.getFieldName() + " " + item.getString());
                if (item.getFieldName().equals("name")) {
                    name = item.getString();
                } else if (item.getFieldName().equals("description")) {
                    description = item.getString();
                } else if (item.getFieldName().equals("unitPrice")) {
                    unitPrice = item.getString();
                } else if (item.getFieldName().equals("quantity")) {
                    quantity = item.getString();
                }
            }
        }

    } catch (FileUploadException ex) {
        System.out.println(ex);
        ex.printStackTrace();
        response.sendRedirect("./addProduct");
    } catch (Exception ex) {
        System.out.println(ex);
        ex.printStackTrace();
        response.sendRedirect("./addProduct");
    }

    FormValidation validation = new FormValidation();
    List<String> messageList = new ArrayList<String>();
    if (!validation.validateAddProduct(name, description, quantity, unitPrice, imageItem)) {
        messageList.addAll(validation.getErrorMessages());
        request.setAttribute("errorMessage", messageList);
        request.setAttribute("name", name);
        request.setAttribute("description", description);
        request.setAttribute("quantity", quantity);
        request.setAttribute("unitPrice", unitPrice);
        RequestDispatcher rd = request.getRequestDispatcher("./addProduct");
        rd.forward(request, response);
    }

    try {
        User user = (User) request.getSession().getAttribute("user");
        productBean.addProduct(name, description, user.getUserId(), Integer.parseInt(quantity),
                Float.parseFloat(unitPrice), imageItem);
        messageList.add("Product Added Successfully.");
        request.setAttribute("successMessage", messageList);
        RequestDispatcher rd = request.getRequestDispatcher("./ViewProductList");
        rd.forward(request, response);
    } catch (Exception e) {
        e.printStackTrace();
        response.sendRedirect("./addProduct");
    }
}

From source file:dk.cphbusiness.codecheck.web.Upload.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request//  w ww .  j a  v  a  2s.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 {
    Enumeration<String> paramNames = request.getParameterNames();
    while (paramNames.hasMoreElements()) {
        String name = paramNames.nextElement();
        String value = request.getParameter(name);
        System.out.println(name + ": " + value);
    }
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {
        try (PrintWriter out = response.getWriter()) {
            out.println("Error: not a multipart request.");
            return;
        }
    }

    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // Configure a repository (to ensure a secure temp location is used)
    //ServletContext servletContext = this.getServletConfig().getServletContext();
    //File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
    File repository = new File(Config.UPLOAD_FOLDER);
    factory.setRepository(repository);

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    int taskID = -1;
    try {
        // Parse the request
        List<FileItem> items = upload.parseRequest(request);
        FileItem ft = null;
        for (FileItem item : items) {
            if (item.isFormField()) {
                if ("TaskID".equals(item.getFieldName())) {
                    taskID = Integer.parseInt(item.getString());
                }
            } else {
                ft = item;
            }
        }
        if (taskID > 0 && ft != null) {
            int reportID = DBUtil.createReport(taskID);
            String fileName = "HandIn_" + reportID + ".jar";
            ft.write(new File(Config.UPLOAD_FOLDER + fileName));
            Task task = DBUtil.getTask(taskID);
            CodeChecker codeChecker = new CodeChecker(reportID, task, fileName);
            Thread t = new Thread(codeChecker);
            t.start();
            //codeChecker.run();
            response.sendRedirect("/CodeCheckWeb/ShowReport?ReportID=" + reportID);
        }
    } catch (FileUploadException ex) {
        Logger.getLogger(Upload.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(Upload.class.getName()).log(Level.SEVERE, null, ex);
    }

}