Commands.UploadImageCommand.java Source code

Java tutorial

Introduction

Here is the source code for Commands.UploadImageCommand.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Commands;

import DAO.ColorDao;
import DAO.ShoesDao;
import DAO.UserDao;
import DTO.Shoes;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author USER
 */
public class UploadImageCommand extends HttpServlet implements Command {

    @Override
    public String executeCommand(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String forwardToJsp = "uploadImage.jsp";
        HttpSession session = request.getSession(true);
        String UPLOAD_DIRECTORY = request.getServletContext().getRealPath("") + File.separator + "img"
                + File.separator;

        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                ArrayList<FileItem> multiparts = (ArrayList<FileItem>) new ServletFileUpload(
                        new DiskFileItemFactory()).parseRequest(request);

                session.setAttribute("errorMsg", multiparts.size());
                if (multiparts.size() > 0) {
                    for (FileItem item : multiparts) {
                        if (item != null) {

                            String name = new File(item.getName()).getName();

                            String filename = UPLOAD_DIRECTORY + name;
                            session.setAttribute("errorMsg", filename);
                            File f = new File(filename);
                            if (!item.isFormField()) {
                                item.write(f);
                            }
                        }
                    }
                } else {
                    session.setAttribute("errorMsg", "No File Choosen");
                }
            } catch (Exception ex) {

            }
        }
        return forwardToJsp;
    }
}