it.unitn.elisco.servlet.ImageUploadServlet.java Source code

Java tutorial

Introduction

Here is the source code for it.unitn.elisco.servlet.ImageUploadServlet.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 it.unitn.elisco.servlet;

import com.google.gson.Gson;
import it.unitn.elisco.bean.hibernate.Person;
import it.unitn.elisco.utils.image.ImageUploader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import org.apache.commons.io.IOUtils;

/**
 *
 * @author Andrea Marcolin
 */
@WebServlet(name = "ImageUploadServlet", urlPatterns = { "/admin/image_upload/*", "/student/image_upload/*" })
@MultipartConfig
public class ImageUploadServlet 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 {

        HttpSession session = request.getSession(false);
        Person user;

        if (request.getRequestURI().equals("/admin/image_upload")) {
            user = (Person) session.getAttribute("admin");
        } else {
            user = (Person) session.getAttribute("student");
        }
        // Get the image uploaded by the user as a stream
        Part imagePart = request.getPart("image");
        String imageExtension = "." + imagePart.getSubmittedFileName().split("\\.")[1];

        // Write to a temp file
        File tempFile = File.createTempFile("tmp", imageExtension);
        tempFile.deleteOnExit();
        FileOutputStream out = new FileOutputStream(tempFile);
        IOUtils.copy(imagePart.getInputStream(), out);

        // Upload the image to Cloudinary
        ImageUploader uploader = ImageUploader.getInstance();
        String imageId = uploader.uploadImageToCloud(user, tempFile);

        // Get the url for the uploaded image
        String imageUrl = uploader.getURLWithDimensions(imageId, 200, 200);

        // Send JSON response back to ajax
        String json = new Gson().toJson(imageUrl);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(json);
    }
}