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

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

Introduction

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

Prototype

public List  parseRequest(HttpServletRequest request) throws FileUploadException 

Source Link

Document

Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a> compliant <code>multipart/form-data</code> stream.

Usage

From source file:it.unisa.tirocinio.servlet.UploadInformationForModuleFilesServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w  w w  .  ja v a  2s .com*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, JSONException {

    try {
        response.setContentType("text/html;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        out = response.getWriter();
        isMultipart = ServletFileUpload.isMultipartContent(request);
        AdministratorDBOperation getSerialNumberObj = new AdministratorDBOperation();
        ConcreteStaff aAdmin = null;
        String serialNumber = null;
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List fileItems = upload.parseRequest(request);
        Iterator i = fileItems.iterator();
        File fileToStore = null;
        String adminSubfolderPath = filePath;
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                DateFormat dateFormat = new SimpleDateFormat("yyyy");
                Date date = new Date();
                if (fieldName.equals("modulefile")) {
                    fileToStore = new File(
                            adminSubfolderPath + fileSeparator + dateFormat.format(date) + " - Module.pdf");
                } else if (fieldName.equals("registerfile")) {
                    fileToStore = new File(
                            adminSubfolderPath + fileSeparator + dateFormat.format(date) + " - Register.pdf");
                }
                fi.write(fileToStore);
                // out.println("Uploaded Filename: " + fieldName + "<br>");
            } else {
                //out.println("It's not formfield");
                //out.println(fi.getString());
                aAdmin = getSerialNumberObj.getFK_DepartimentbyFK_Account(Integer.parseInt(fi.getString()));
                serialNumber = "" + aAdmin.getFKDepartment();
                adminSubfolderPath += fileSeparator + serialNumber;
                new File(adminSubfolderPath).mkdir();
            }
        }
        message.put("status", 1);
        out.print(message.toString());
    } catch (IOException ex) {
        message.put("status", 0);
        message.put("errorMessage", ex);
        out.print(message.toString());
        Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ClassNotFoundException ex) {
        message.put("status", 0);
        message.put("errorMessage", ex);
        out.print(message.toString());
        Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        message.put("status", 0);
        message.put("errorMessage", ex);
        out.print(message.toString());
        Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (FileUploadException ex) {
        message.put("status", 0);
        message.put("errorMessage", ex);
        out.print(message.toString());
        Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        message.put("status", 0);
        message.put("errorMessage", ex);
        out.print(message.toString());
        Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        out.close();
    }
}

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

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*//*from  w w w  .j  av a  2  s  .c o  m*/
@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)) {
            name = "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;

            while (it.hasNext()) {
                FileItem fileItem = (FileItem) it.next();
                result += "CreateVocab: Form Field: " + fileItem.isFormField() + " Field name: "
                        + fileItem.getFieldName() + " Name: " + fileItem.getName() + " String: "
                        + fileItem.getString() + "\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();
                } else {

                    @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 {
                    //               status = "Form is not multi-part";
                    //               vocabName = request.getParameter("vocab-name");
                    //               String vocabs = request.getParameter("vocab-terms");
                    MetaDbHelper.note(vocabs);
                    for (String vocab : vocabs.split("\n"))
                        vocabList.add(vocab);
                }
                if (!vocabList.isEmpty()) {
                    if (ControlledVocabDAO.addControlledVocab(vocabName, vocabList))
                        status = "Vocab " + vocabName + " created successfully";
                    else if (ControlledVocabDAO.updateControlledVocab(vocabName, vocabList))
                        status = "Vocab " + vocabName + " updated successfully ";
                    else
                        status = "Vocab " + vocabName + " cannot be updated/created";
                }
            }
        }
    } catch (Exception e) {
        MetaDbHelper.logEvent(e);
    }
    MetaDbHelper.note(status);
    out.print(status);
    out.flush();
}

From source file:Controller.ControllerProducts.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/* w w  w  .  j a va2 s  .  com*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {

    } else {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items = null;
        try {
            items = upload.parseRequest(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Iterator iter = items.iterator();
        Hashtable params = new Hashtable();
        String fileName = null;
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) {
                params.put(item.getFieldName(), item.getString());
            } else {

                try {
                    String itemName = item.getName();
                    fileName = itemName.substring(itemName.lastIndexOf("\\") + 1);
                    System.out.println("path" + fileName);
                    String RealPath = getServletContext().getRealPath("/") + "upload\\" + fileName;
                    System.out.println("Rpath" + RealPath);
                    File savedFile = new File(RealPath);
                    item.write(savedFile);
                    //System.out.println("upload\\"+fileName);
                    //insert Product
                    String code = (String) params.get("txtcode");
                    String name = (String) params.get("txtname");
                    String price = (String) params.get("txtprice");
                    Products sp = new Products();
                    sp.InsertProduct(code, name, price, "upload\\" + fileName);
                    RequestDispatcher rd = request.getRequestDispatcher("product.jsp");
                    rd.forward(request, response);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }

    }
    //this.processRequest(request, response);
}

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

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

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

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

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

From source file:com.GTDF.server.FileUploadServlet.java

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

    String rootDirectory = getServletConfig().getInitParameter("TRANSFORM_HOME");
    String workDirectory = getServletConfig().getInitParameter("TRANSFORM_DIR");
    String prefixDirectory = "";
    boolean writeToFile = true;
    String returnOKMessage = "OK";
    String username = "";
    String authResult = "";

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    PrintWriter out = response.getWriter();

    // Create a factory for disk-based file items 
    if (isMultipart) {

        // We are uploading a file (deletes are performed by non multipart requests) 
        FileItemFactory factory = new DiskFileItemFactory();

        // Create a new file upload handler 
        ServletFileUpload upload = new ServletFileUpload(factory);
        // Parse the request 
        try {/* w  w  w  .j a v a  2  s  . c  o  m*/

            List items = upload.parseRequest(request);

            // Process the uploaded items 
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField()) {

                    // Hidden field containing username - check authorization
                    if (item.getFieldName().equals("username")) {
                        username = item.getString();
                        String wikiDb = getServletConfig().getInitParameter("WIKIDB");
                        String wikiDbUser = getServletConfig().getInitParameter("WIKIDB_USER");
                        String wikiDbPassword = getServletConfig().getInitParameter("WIKIDB_PASSWORD");
                        String wikiNoAuth = getServletConfig().getInitParameter("NOAUTH"); // v1.5 Check parameter NOAUTH
                        WikiUserImpl wikiUser = new WikiUserImpl();
                        authResult = wikiUser.wikiUserVerifyDb(username, wikiDb, wikiDbUser, wikiDbPassword,
                                wikiNoAuth);
                        if (authResult != "LOGGED") {
                            out.print(authResult);
                            return;
                        } else
                            new File(rootDirectory + workDirectory + '/' + username).mkdirs();
                    }

                    // Hidden field containing file prefix to create subdirectory
                    if (item.getFieldName().equals("prefix")) {
                        prefixDirectory = item.getString();
                        new File(rootDirectory + workDirectory + '/' + username + '/' + prefixDirectory)
                                .mkdirs();
                        prefixDirectory += '/';
                    }
                } else {
                    if (writeToFile) {
                        String fileName = item.getName();
                        if (fileName != null && !fileName.equals("")) {
                            fileName = FilenameUtils.getName(fileName);
                            File uploadedFile = new File(rootDirectory + workDirectory + '/' + username + '/'
                                    + prefixDirectory + fileName);
                            try {
                                item.write(uploadedFile);
                                String hostedOn = getServletConfig().getInitParameter("HOSTED_ON");
                                out.print("Infile at: " + hostedOn + workDirectory + '/' + username + '/'
                                        + prefixDirectory + fileName);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    } else {
                    }
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
    } else {

        //Process a request to delete a file 
        String[] paramValues = request.getParameterValues("uploadFormElement");
        for (int i = 0; i < paramValues.length; i++) {
            String fileName = FilenameUtils.getName(paramValues[i]);
            File deleteFile = new File(rootDirectory + workDirectory + fileName);
            if (deleteFile.delete()) {
                out.print(returnOKMessage);
            }
        }
    }

}

From source file:com.liferay.apio.architect.impl.jaxrs.json.reader.MultipartBodyMessageBodyReader.java

@Override
public Body readFrom(Class<Body> clazz, Type genericType, Annotation[] annotations, MediaType mediaType,
        MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException {

    if (!isMultipartContent(_httpServletRequest)) {
        throw new BadRequestException("Request body is not a valid multipart form");
    }/*from   ww  w. ja v  a 2 s .  c  o  m*/

    FileItemFactory fileItemFactory = new DiskFileItemFactory();

    ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);

    try {
        List<FileItem> fileItems = servletFileUpload.parseRequest(_httpServletRequest);

        Iterator<FileItem> iterator = fileItems.iterator();

        Map<String, String> values = new HashMap<>();
        Map<String, BinaryFile> binaryFiles = new HashMap<>();
        Map<String, Map<Integer, String>> indexedValueLists = new HashMap<>();
        Map<String, Map<Integer, BinaryFile>> indexedFileLists = new HashMap<>();

        while (iterator.hasNext()) {
            FileItem fileItem = iterator.next();

            String name = fileItem.getFieldName();

            Matcher matcher = _arrayPattern.matcher(name);

            if (matcher.matches()) {
                int index = Integer.parseInt(matcher.group(2));

                String actualName = matcher.group(1);

                _storeFileItem(fileItem, value -> {
                    Map<Integer, String> indexedMap = indexedValueLists.computeIfAbsent(actualName,
                            __ -> new HashMap<>());

                    indexedMap.put(index, value);
                }, binaryFile -> {
                    Map<Integer, BinaryFile> indexedMap = indexedFileLists.computeIfAbsent(actualName,
                            __ -> new HashMap<>());

                    indexedMap.put(index, binaryFile);
                });
            } else {
                _storeFileItem(fileItem, value -> values.put(name, value),
                        binaryFile -> binaryFiles.put(name, binaryFile));
            }
        }

        Map<String, List<String>> valueLists = _flattenMap(indexedValueLists);

        Map<String, List<BinaryFile>> fileLists = _flattenMap(indexedFileLists);

        return Body.create(key -> Optional.ofNullable(values.get(key)),
                key -> Optional.ofNullable(valueLists.get(key)), key -> Optional.ofNullable(fileLists.get(key)),
                key -> Optional.ofNullable(binaryFiles.get(key)));
    } catch (FileUploadException | IndexOutOfBoundsException | NumberFormatException e) {

        throw new BadRequestException("Request body is not a valid multipart form", e);
    }
}

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

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

From source file:imageServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from   ww w  .j  a  v a2  s .  c om*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String name = "";
    String value = "";
    String imageurl = "";
    String path = "";
    try {
        String ImageFile = "";
        String itemName = "";

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart) {
        } else {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = null;
            try {
                items = upload.parseRequest(request);
            } catch (FileUploadException e) {
                System.out.println("Exception in upload");
                e.getMessage();
            }

            Iterator itr = items.iterator();
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();
                if (item.isFormField()) {
                    name = item.getFieldName();
                    value = item.getString();
                    if (name.equals("ImageFile")) {
                        ImageFile = value;
                    }

                } else {
                    try {

                        itemName = item.getName();
                        File savedFile = new File(
                                this.getServletContext().getRealPath("/") + "images\\" + itemName);
                        File image = new File(request.getParameter("ImageFile"));
                        path = "/images/";
                        name = itemName;
                        item.write(savedFile);
                    } catch (Exception e) {
                        System.out.println("Error" + e.getMessage());
                    }
                }
            }
            try {
                int image = StudyDB.uploadImage("/images/" + itemName);
                imageurl = StudyDB.retrieveImage();

            } catch (Exception el) {
                System.out.println("Inserting error" + el.getMessage());
            }
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
    String URL = "/displayImage.jsp";
    String message = "Success";
    request.setAttribute("message", message);
    request.setAttribute("imageurl", imageurl);
    getServletContext().getRequestDispatcher(URL).forward(request, response);

}

From source file:br.edu.ifpb.ads.psd.projeto.servlets.UploadImagemPerfil.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from   w w  w.  j a  v  a2 s.co  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Usuario usuario = ((Usuario) request.getSession().getAttribute("usuario"));
    if (usuario == null) {
        response.sendRedirect("");
    } else {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = null;
            try {
                items = (List<FileItem>) upload.parseRequest(request);
            } catch (FileUploadException ex) {
                Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex);
            }
            FileItem item = items.get(0);
            if (item != null) {
                String nome_arquivo = String.valueOf(new Date().getTime()) + item.getName();
                String caminho = getServletContext().getRealPath("/imagens") + "\\" + usuario.getId() + "\\";
                File file = new File(caminho);
                if (!file.exists()) {
                    file.mkdirs();
                }
                File uploadedFile = new File(caminho + nome_arquivo);
                try {
                    item.write(uploadedFile);
                } catch (Exception ex) {
                    Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex);
                }
                GerenciadorDeUsuario gerenciarUsuario = new GerenciadorDeUsuario();
                try {
                    gerenciarUsuario.atualizarFotoPerfil("imagens" + "/" + usuario.getId() + "/" + nome_arquivo,
                            usuario.getId());
                } catch (SQLException ex) {
                    Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex);
                }
                GerenciarFotos gerenciarFotos = new GerenciarFotos();
                try {
                    gerenciarFotos.publicarFoto("imagens" + "/" + usuario.getId() + "/" + nome_arquivo,
                            usuario);
                } catch (SQLException ex) {
                    Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex);
                }
                try {
                    usuario = gerenciarUsuario.getUsuario(usuario.getId());
                } catch (SQLException ex) {
                    Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex);
                }
                request.getSession().setAttribute("usuario", usuario);
                response.sendRedirect("configuracao");
            } else {

            }
        }

    }
}

From source file:com.mylop.servlet.TimelineServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from www.  j  a v  a  2 s  .c o m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json");
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    HttpSession session = request.getSession();
    String userid = (String) session.getAttribute("userid");
    String status = "aaa";
    String urlTimelineImage = "";
    String title = "";
    String subtitle = "";
    String content = "";
    Date date = new Date(Calendar.getInstance().getTimeInMillis());
    TimelineModel tm = new TimelineModel();
    if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            List<FileItem> multiparts = upload.parseRequest(request);
            for (FileItem item : multiparts) {

                if (!item.isFormField()) {
                    String contentType = item.getContentType();
                    String fileName = UPLOAD_DIRECTORY + File.separator + userid + "_"
                            + (tm.getLastIndex() + 1);
                    File file = new File(fileName);
                    item.write(file);
                    urlTimelineImage = "http://mylop.tk:8080/Timeline/" + file.getName();
                } else {
                    String fieldName = item.getFieldName();

                    if (fieldName.equals("title")) {
                        title = item.getString();
                    }
                    if (fieldName.equals("subtitle")) {
                        subtitle = item.getString();
                    }
                    if (fieldName.equals("content")) {
                        content = item.getString();
                    }
                    if (fieldName.equals("date")) {
                        Long dateLong = Long.parseLong(item.getString());
                        date = new Date(dateLong);
                    }

                }
            }

            tm.addTimeline(userid, title, subtitle, date, content, urlTimelineImage);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    String json = "{\"message\": \"success\"}";
    response.getWriter().write(json);
}