com.viseur.control.UploadImageServlet.java Source code

Java tutorial

Introduction

Here is the source code for com.viseur.control.UploadImageServlet.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 com.viseur.control;

import com.viseur.model.FileUpload;
import com.viseur.model.VHost;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import org.json.JSONObject;

/**
 *
 * @author JHK
 */
@MultipartConfig
public class UploadImageServlet extends HttpServlet {

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @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
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Part imgPart = request.getPart("imageupload");
        String extension = request.getParameter("extension");
        int maxMB = Integer.valueOf(request.getParameter("maxsize"));

        //   String contextPath = request.getServletContext().getRealPath(""); //Files will be stored inside BUILD folder
        String imgName = UUID.randomUUID().toString();
        String filePath = "/temp/" + imgName + extension;
        String destination = VHost.UPLOAD + filePath;
        FileUpload imgUpload = new FileUpload(extension, maxMB, destination);
        boolean success = imgUpload.NewFileUpload(imgPart);

        JSONObject json = new JSONObject();
        json.put("success", success);
        if (success) {
            json.put("img", imgName);
            json.put("imgUrl", filePath);
        } else {
            json.put("error", imgUpload.error.mMessage);
        }

        try (PrintWriter out = response.getWriter()) {
            out.print(json);
            out.flush();
        }

    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Image Upload";
    }

}