Example usage for org.apache.commons.fileupload FileItem write

List of usage examples for org.apache.commons.fileupload FileItem write

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem write.

Prototype

void write(File file) throws Exception;

Source Link

Document

A convenience method to write an uploaded item to disk.

Usage

From source file:productsave.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    try {//  ww  w. jav a 2  s. com
        ServletContext x = this.getServletContext();
        String path = x.getRealPath("/images");

        System.out.println(path + " path");
        DiskFileUpload p = new DiskFileUpload();
        List q = p.parseRequest(request);
        Iterator z = q.iterator();
        while (z.hasNext()) {
            FileItem f = (FileItem) z.next();
            if (f.isFormField() == true) {
                //non-file data
                System.out.println("executed");
                String h = f.getFieldName();
                String data = f.getString();
                if (h.equalsIgnoreCase("productname")) {
                    productname = data;
                } else if (h.equalsIgnoreCase("category")) {
                    categoryid = data;
                    System.out.println(categoryid + " cccc");
                } else if (h.equalsIgnoreCase("price")) {
                    price = data;
                } else if (h.equalsIgnoreCase("description")) {
                    description = data;
                }

            } else {
                //file data
                String filename = f.getName();
                if (filename != null && filename.length() > 0) {
                    File g = new File(filename);

                    filename = g.getName();

                    //creating unique file name
                    long w = System.currentTimeMillis();
                    filename = w + filename;
                    System.out.println("path " + path + " file " + filename);
                    //upload file
                    File t = new File(path, filename);
                    f.write(t);
                    if (f.getFieldName().equals("image")) {
                        image = filename;
                    }
                }

            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    productbean product = new productbean();
    product.setProductname(productname);
    product.setCategoryid(categoryid);
    product.setDescription(description);
    product.setImage(image);
    product.setPrice(price);
    int count = product.save();
    if (count != 0) {
        out.println("1");
    } else {
        out.println("0");
    }
}

From source file:edu.xtec.colex.client.beans.ColexRecordBean.java

/**
 * Calls the web service operation// ww  w. ja  va 2s  .c o  m
 * <I>modifyRecord(User,Owner,Collection,Record) : void</I>
 *
 * @param r the Record to modify
 * @param vAttachments a Vector containing the Attachments of the Record
 * @throws java.lang.Exception when an Exception error occurs
 */
protected void modifyRecord(Record r, Vector vAttachments) throws Exception {
    User u = new User(getUserId());

    Collection c = new Collection("");

    c.setName(collection);

    try {
        smRequest = mf.createMessage();

        SOAPBodyElement sbeRequest = setRequestName(smRequest, "modifyRecord");

        addParam(sbeRequest, u);
        if (owner != null) {
            Owner oRequest = new Owner(owner);
            addParam(sbeRequest, oRequest);
        }
        addParam(sbeRequest, c);
        addParam(sbeRequest, r);

        for (int i = 0; i < vAttachments.size(); i++) {

            FileItem fi = (FileItem) vAttachments.get(i);

            String sNomFitxer = Utils.getFileName(fi.getName());

            File fTemp = File.createTempFile("attach", null);

            fi.write(fTemp);

            URL urlFile = new URL("file://" + fTemp.getPath());

            AttachmentPart ap = smRequest.createAttachmentPart(new DataHandler(urlFile));

            String fieldName = fi.getFieldName();

            ap.setContentId(fieldName + "/" + sNomFitxer);

            smRequest.addAttachmentPart(ap);
        }

        smRequest.saveChanges();

        SOAPMessage smResponse = sendMessage(smRequest,
                this.getJspProperties().getProperty("url.servlet.record"));

        SOAPBody sbResponse = smResponse.getSOAPBody();

        if (sbResponse.hasFault()) {
            checkFault(sbResponse, "modify");
        } else {

        }
    } catch (SOAPException se) {
        throw se;
    }
}

From source file:adminpackage.adminview.UpdateProductServlet.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    String value = "defa";
    AdminUpdateProductWrapper product = new AdminUpdateProductWrapper();

    try {/*from www .ja va  2s  .  c  om*/
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = upload.parseRequest(request);
        Iterator itr = items.iterator();
        String url = "";
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            if (item.isFormField()) {
                String name = item.getFieldName();
                value = item.getString();
                switch (name) {
                case "pid":
                    product.setId(Integer.parseInt(value));
                    break;
                case "pname":
                    product.setName(value);
                    break;
                case "quantity":
                    product.setQuantity(Integer.parseInt(value));
                    break;
                case "author":
                    product.setAuthor(value);
                    break;
                case "isbn":
                    product.setISBN(Long.parseLong(value));
                    break;
                case "description":
                    product.setDescription(value);
                    break;
                case "category":
                    product.setCategory(value);
                    break;
                case "price":
                    product.setPrice(Integer.parseInt(value));
                    break;
                }
            } else {

                try {
                    if (item.getName().length() > 0) {
                        item.write(new File(context.getRealPath("/pages/images/").replaceAll(
                                "\\\\target\\\\MavenOnlineShoping-1.0-SNAPSHOT", "\\\\src\\\\main\\\\webapp")
                                + item.getName()));
                        //System.out.println(context.getRealPath("/pages/images/").replaceAll("\\\\target\\\\MavenOnlineShoping-1.0-SNAPSHOT", "\\\\src\\\\main\\\\webapp") + item.getName());
                        //url = context.getRealPath("/pages/images/").replaceAll("\\\\target\\\\MavenOnlineShoping-1.0-SNAPSHOT", "\\\\src\\\\main\\\\webapp") + item.getName();
                        UUID idOne = UUID.randomUUID();
                        product.setImage(
                                idOne.toString() + item.getName().substring(item.getName().length() - 4));
                    }
                } catch (Exception ex) {
                    Logger.getLogger(UpdateProductServlet.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    } catch (FileUploadException ex) {
        Logger.getLogger(UpdateProductServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

    System.out.println("adminpackage.adminview.UpdateProductServlet.processRequest()");
    out.print(adminFacadeHandler.UpdateProduct(product));
    if (value != null) {

    }

}

From source file:com.lushapp.common.web.servlet.kindeditor.FileUploadServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String dirName = request.getParameter("dir");
    if (dirName == null) {
        dirName = "image";
    }//from w  w  w. j a v  a  2 s.c  o  m

    //?
    String uploadPath = getInitParameter("UPLOAD_PATH");
    if (StringUtils.isNotBlank(uploadPath)) {
        configPath = uploadPath;
    }

    if ("image".equals(dirName)) {

        //?
        Long size = Long.parseLong(getInitParameter("Img_MAX_SIZE"));
        if (size != null) {
            maxSize = size;
        }

        //(?gif, jpg, jpeg, png, bmp)
        String type = getInitParameter("Img_YPES");
        if (StringUtils.isNotBlank(type)) {
            extMap.put("image", type);
        }

    } else {
        //?
        Long size = Long.parseLong(getInitParameter("File_MAX_SIZE"));
        if (size != null) {
            maxSize = size;
        }

        if ("file".equals(dirName)) {
            //(doc, xls, ppt, pdf, txt, rar, zip)
            String type = getInitParameter("File_TYPES");
            if (StringUtils.isNotBlank(type)) {
                extMap.put("file", type);
            }
        }
    }

    if (StringUtils.isBlank(configPath)) {
        WebUtils.renderText(response, getError("?!"));
        return;
    }

    //?
    String savePath = this.getServletContext().getRealPath("/") + configPath;

    //?URL
    String saveUrl = request.getContextPath() + "/" + configPath;

    if (!ServletFileUpload.isMultipartContent(request)) {
        WebUtils.renderText(response, getError(""));
        return;
    }
    //
    File uploadDir = new File(savePath);
    if (!uploadDir.isDirectory()) {
        FileUtil.createDirectory(uploadDir.getPath());
        //         ServletUtils.rendText(getError("?"), response);
        //         return;
    }
    //??
    if (!uploadDir.canWrite()) {
        WebUtils.renderText(response, getError("??"));
        return;
    }

    if (!extMap.containsKey(dirName)) {
        WebUtils.renderText(response, getError("???"));
        return;
    }
    //
    savePath += dirName + "/";
    saveUrl += dirName + "/";
    File saveDirFile = new File(savePath);
    if (!saveDirFile.exists()) {
        saveDirFile.mkdirs();
    }
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    String ymd = sdf.format(new Date());
    savePath += ymd + "/";
    saveUrl += ymd + "/";
    File dirFile = new File(savePath);
    if (!dirFile.exists()) {
        dirFile.mkdirs();
    }

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("UTF-8");

    try {
        List items = upload.parseRequest(request);
        Iterator itr = items.iterator();
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            String fileName = item.getName();
            long fileSize = item.getSize();
            if (!item.isFormField()) {
                //?
                if (item.getSize() > maxSize) {
                    WebUtils.renderText(response, getError("??"));
                    return;
                }
                //??
                String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                if (!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)) {
                    WebUtils.renderText(response,
                            getError("??????\n??"
                                    + extMap.get(dirName) + "?"));
                    return;
                }

                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
                try {
                    File uploadedFile = new File(savePath, newFileName);
                    item.write(uploadedFile);
                } catch (Exception e) {
                    WebUtils.renderText(response, getError(""));
                    return;
                }

                Map<String, Object> obj = Maps.newHashMap();
                obj.put("error", 0);
                obj.put("url", saveUrl + newFileName);
                WebUtils.renderText(response, obj);
            }
        }
    } catch (FileUploadException e1) {
        e1.printStackTrace();
    }

}

From source file:edu.xtec.colex.client.beans.ColexRecordBean.java

/**
 * Calls the web service operation//from  w w  w. ja  v a 2 s.  co m
 * <I>addRecord(User,Owner,Collection,Record) : void</I>
 *
 * @param r the Record to add
 * @param vAttachments a Vector containing the Attachments of the Record
 * @throws java.lang.Exception when an Exception error occurs
 */
protected void addRecord(Record r, Vector vAttachments) throws Exception {
    User u = new User(getUserId());
    Collection c = new Collection("");

    Vector vTempFiles = new Vector();

    c.setName(collection);

    try {
        smRequest = mf.createMessage();

        SOAPBodyElement sbeRequest = setRequestName(smRequest, "addRecord");

        addParam(sbeRequest, u);
        if (owner != null) {
            Owner oRequest = new Owner(owner);
            addParam(sbeRequest, oRequest);
        }
        addParam(sbeRequest, c);
        addParam(sbeRequest, r);

        for (int i = 0; i < vAttachments.size(); i++) {

            FileItem fi = (FileItem) vAttachments.get(i);

            String sNomFitxer = Utils.getFileName(fi.getName());

            File fTemp = File.createTempFile("attach", null);

            fi.write(fTemp);

            vTempFiles.add(fTemp);

            URL urlFile = new URL("file://" + fTemp.getPath());

            AttachmentPart ap = smRequest.createAttachmentPart(new DataHandler(urlFile));

            String fieldName = fi.getFieldName();

            ap.setContentId(fieldName + "/" + sNomFitxer);

            smRequest.addAttachmentPart(ap);
        }
        smRequest.saveChanges();

        SOAPMessage smResponse = sendMessage(smRequest,
                this.getJspProperties().getProperty("url.servlet.record"));

        SOAPBody sbResponse = smResponse.getSOAPBody();

        if (sbResponse.hasFault()) {
            checkFault(sbResponse, "add");
        } else {

        }
    } catch (Exception e) {
        throw e;
    } finally {
        File fAux;

        for (int i = 0; i < vTempFiles.size(); i++) {
            fAux = (File) vTempFiles.get(i);
            fAux.delete();
        }
    }
}

From source file:com.eryansky.common.web.servlet.kindeditor.FileUploadServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String dirName = request.getParameter("dir");
    if (dirName == null) {
        dirName = "image";
    }/*  w w  w  . j a  v a  2s.co  m*/

    //?
    String uploadPath = getInitParameter("UPLOAD_PATH");
    if (StringUtils.isNotBlank(uploadPath)) {
        configPath = uploadPath;
    }

    if ("image".equals(dirName)) {

        //?
        Long size = Long.parseLong(getInitParameter("Img_MAX_SIZE"));
        if (size != null) {
            maxSize = size;
        }

        //(?gif, jpg, jpeg, png, bmp)
        String type = getInitParameter("Img_YPES");
        if (StringUtils.isNotBlank(type)) {
            extMap.put("image", type);
        }

    } else {
        //?
        Long size = Long.parseLong(getInitParameter("File_MAX_SIZE"));
        if (size != null) {
            maxSize = size;
        }

        if ("file".equals(dirName)) {
            //(doc, xls, ppt, pdf, txt, rar, zip)
            String type = getInitParameter("File_TYPES");
            if (StringUtils.isNotBlank(type)) {
                extMap.put("file", type);
            }
        }
    }

    if (StringUtils.isBlank(configPath)) {
        ServletUtils.renderText(getError("?!"), response);
        return;
    }

    //?
    String savePath = this.getServletContext().getRealPath("/") + configPath;

    //?URL
    String saveUrl = request.getContextPath() + "/" + configPath;

    if (!ServletFileUpload.isMultipartContent(request)) {
        ServletUtils.renderText(getError(""), response);
        return;
    }
    //
    File uploadDir = new File(savePath);
    if (!uploadDir.isDirectory()) {
        FileUtil.createDirectory(uploadDir.getPath());
        //         ServletUtils.rendText(getError("?"), response);
        //         return;
    }
    //??
    if (!uploadDir.canWrite()) {
        ServletUtils.renderText(getError("??"), response);
        return;
    }

    if (!extMap.containsKey(dirName)) {
        ServletUtils.renderText(getError("???"), response);
        return;
    }
    //
    savePath += dirName + "/";
    saveUrl += dirName + "/";
    File saveDirFile = new File(savePath);
    if (!saveDirFile.exists()) {
        saveDirFile.mkdirs();
    }
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    String ymd = sdf.format(new Date());
    savePath += ymd + "/";
    saveUrl += ymd + "/";
    File dirFile = new File(savePath);
    if (!dirFile.exists()) {
        dirFile.mkdirs();
    }

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("UTF-8");

    try {
        List items = upload.parseRequest(request);
        Iterator itr = items.iterator();
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            String fileName = item.getName();
            long fileSize = item.getSize();
            if (!item.isFormField()) {
                //?
                if (item.getSize() > maxSize) {
                    ServletUtils.renderText(getError("??"), response);
                    return;
                }
                //??
                String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                if (!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)) {
                    ServletUtils
                            .renderText(getError("??????\n??"
                                    + extMap.get(dirName) + "?"), response);
                    return;
                }

                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
                try {
                    File uploadedFile = new File(savePath, newFileName);
                    item.write(uploadedFile);
                } catch (Exception e) {
                    ServletUtils.renderText(getError(""), response);
                    return;
                }

                Map<String, Object> obj = Maps.newHashMap();
                obj.put("error", 0);
                obj.put("url", saveUrl + newFileName);
                ServletUtils.renderText(obj, response);
            }
        }
    } catch (FileUploadException e1) {
        e1.printStackTrace();
    }

}

From source file:com.github.podd.resources.UploadArtifactResourceImpl.java

private InferredOWLOntologyID uploadFileAndLoadArtifactIntoPodd(final Representation entity)
        throws ResourceException {
    List<FileItem> items;/* www  . j a va  2s  .  com*/
    Path filePath = null;
    String contentType = null;

    // 1: Create a factory for disk-based file items
    final DiskFileItemFactory factory = new DiskFileItemFactory(1000240, this.tempDirectory.toFile());

    // 2: Create a new file upload handler
    final RestletFileUpload upload = new RestletFileUpload(factory);
    final Map<String, String> props = new HashMap<String, String>();
    try {
        // 3: Request is parsed by the handler which generates a list of
        // FileItems
        items = upload.parseRequest(this.getRequest());

        for (final FileItem fi : items) {
            final String name = fi.getName();

            if (name == null) {
                props.put(fi.getFieldName(), new String(fi.get(), StandardCharsets.UTF_8));
            } else {
                // FIXME: Strip everything up to the last . out of the
                // filename so that
                // the filename can be used for content type determination
                // where
                // possible.
                // InputStream uploadedFileInputStream =
                // fi.getInputStream();
                try {
                    // Note: These are Java-7 APIs
                    contentType = fi.getContentType();
                    props.put("Content-Type", fi.getContentType());

                    filePath = Files.createTempFile(this.tempDirectory, "ontologyupload-", name);
                    final File file = filePath.toFile();
                    file.deleteOnExit();
                    fi.write(file);
                } catch (final IOException ioe) {
                    throw ioe;
                } catch (final Exception e) {
                    // avoid throwing a generic exception just because the
                    // apache
                    // commons library throws Exception
                    throw new IOException(e);
                }
            }
        }
    } catch (final IOException | FileUploadException e) {
        throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, e);
    }

    this.log.info("props={}", props.toString());

    if (filePath == null) {
        throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST,
                "Did not submit a valid file and filename");
    }

    this.log.info("filename={}", filePath.toAbsolutePath().toString());
    this.log.info("contentType={}", contentType);

    RDFFormat format = null;

    // If the content type was application/octet-stream then use the file
    // name instead
    // Browsers attach this content type when they are not sure what the
    // real type is
    if (MediaType.APPLICATION_OCTET_STREAM.getName().equals(contentType)) {
        format = Rio.getParserFormatForFileName(filePath.getFileName().toString());

        this.log.info("octet-stream contentType filename format={}", format);
    }
    // Otherwise use the content type directly in preference to using the
    // filename
    else if (contentType != null) {
        format = Rio.getParserFormatForMIMEType(contentType);

        this.log.info("non-octet-stream contentType format={}", format);
    }

    // If the content type choices failed to resolve the type, then try the
    // filename
    if (format == null) {
        format = Rio.getParserFormatForFileName(filePath.getFileName().toString());

        this.log.info("non-content-type filename format={}", format);
    }

    // Or fallback to RDF/XML which at minimum is able to detect when the
    // document is
    // structurally invalid
    if (format == null) {
        this.log.warn("Could not determine RDF format from request so falling back to RDF/XML");
        format = RDFFormat.RDFXML;
    }

    try (final InputStream inputStream = new BufferedInputStream(
            Files.newInputStream(filePath, StandardOpenOption.READ));) {
        return this.uploadFileAndLoadArtifactIntoPodd(inputStream, format, DanglingObjectPolicy.REPORT,
                DataReferenceVerificationPolicy.DO_NOT_VERIFY);
    } catch (final IOException e) {
        throw new ResourceException(Status.SERVER_ERROR_INTERNAL, "File IO error occurred", e);
    }

}

From source file:com.sketchy.server.UpgradeUploadServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    JSONServletResult jsonServletResult = new JSONServletResult(Status.SUCCESS);
    try {/*from  www  .java  2s  . c  o m*/

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {

            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setRepository(FileUtils.getTempDirectory());
            factory.setSizeThreshold(MAX_SIZE);

            ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
            List<FileItem> files = servletFileUpload.parseRequest(request);
            String version = "";
            for (FileItem fileItem : files) {
                String uploadFileName = fileItem.getName();
                if (StringUtils.isNotBlank(uploadFileName)) {

                    JarInputStream jarInputStream = null;
                    try {
                        // check to make sure it's a Sketchy File with a Manifest File
                        jarInputStream = new JarInputStream(fileItem.getInputStream(), true);
                        Manifest manifest = jarInputStream.getManifest();
                        if (manifest == null) {
                            throw new Exception("Invalid Upgrade File!");
                        }
                        Attributes titleAttributes = manifest.getMainAttributes();
                        if ((titleAttributes == null) || (!StringUtils.containsIgnoreCase(
                                titleAttributes.getValue("Implementation-Title"), "Sketchy"))) {
                            throw new Exception("Invalid Upgrade File!");
                        }
                        version = titleAttributes.getValue("Implementation-Version");
                    } catch (Exception e) {
                        throw new Exception("Invalid Upgrade File!");
                    } finally {
                        IOUtils.closeQuietly(jarInputStream);
                    }
                    // save new .jar file as "ready"
                    fileItem.write(new File("Sketchy.jar.ready"));
                    jsonServletResult.put("version", version);
                }
            }
        }
    } catch (Exception e) {
        jsonServletResult = new JSONServletResult(Status.ERROR, e.getMessage());
    }
    response.setContentType("text/html");
    response.setStatus(HttpServletResponse.SC_OK);
    response.getWriter().print(jsonServletResult.toJSONString());
}

From source file:admin.controller.ServletUploadFonts.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*ww  w . ja va2 s  .c om*/
 *
 * @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:adminServlets.AddProductServlet.java

private void uploadImage(HttpServletRequest request, HttpServletResponse response) {
    PrintWriter out = null;/*from  w w  w  .j  a v  a2 s  . c  o  m*/
    try {

        out = response.getWriter();
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> iter = items.iterator();

        while (iter.hasNext()) {

            FileItem item = (FileItem) iter.next();

            if (item.isFormField()) {
                String name = item.getFieldName();
                String value = item.getString();
                paramaters.put(name, value);

            } else // processUploadedFile(item);
            {
                if (item.getSize() != 0) {
                    String itemName = item.getName();
                    Random generator = new Random();
                    int r = Math.abs(generator.nextInt());

                    String reg = "[.*]";
                    String replacingtext = "";

                    Pattern pattern = Pattern.compile(reg);
                    Matcher matcher = pattern.matcher(itemName);
                    StringBuffer buffer = new StringBuffer();

                    while (matcher.find()) {
                        matcher.appendReplacement(buffer, replacingtext);
                    }
                    int IndexOf = itemName.indexOf(".");
                    String domainName = itemName.substring(IndexOf);

                    String finalimage = buffer.toString() + "_" + r + domainName;

                    String path = "assets\\img\\bouques\\" + finalimage;
                    imgPaths.add(path);
                    File savedFile = new File(getServletContext().getRealPath("/") + path);

                    try {
                        item.write(savedFile);
                    } catch (Exception ex) {
                        Logger.getLogger(AddProductServlet.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        }
    } catch (IOException | FileUploadException ex) {
        Logger.getLogger(AddProductServlet.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
    }

}