com.vigglet.oei.technician.UploadProfilePhoto.java Source code

Java tutorial

Introduction

Here is the source code for com.vigglet.oei.technician.UploadProfilePhoto.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.vigglet.oei.technician;

import com.vigglet.oei.content.Content;
import com.vigglet.oei.content.ContentUtil;
import com.vigglet.oei.user.User;
import com.vigglet.servlet.BaseServlet;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import org.apache.commons.io.IOUtils;

/**
 *
 * @author vikn
 */
@WebServlet(name = "fileUploadServlet", urlPatterns = { "/api/technician/upload/photo" })
@MultipartConfig(fileSizeThreshold = 0, maxFileSize = 20971520) // 20 MB
public class UploadProfilePhoto extends BaseServlet {

    private static final Logger logger = Logger.getLogger(UploadProfilePhoto.class.getName());

    @Override
    protected void preProcessRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            User user = getUser(req);

            for (Part part : req.getParts()) {
                byte[] b = IOUtils.toByteArray(part.getInputStream());
                String fileName = extractFileName(part);

                File file = new File(Content.FILE_LOCATION + "/" + fileName);
                FileOutputStream fos = new FileOutputStream(file);
                ByteArrayInputStream bais = new ByteArrayInputStream(b);
                IOUtils.copy(bais, fos);

                fos.flush();
                fos.close();
                bais.close();

                Content content = new Content();
                content.setCompany(user.getCompany());
                content.setUser(user.getId());
                content.setName(file.getName());
                content.setFilesize((int) file.length());
                content.setLocation(file.getAbsolutePath());

                ContentUtil.getInstance().insertOrUpdate(content);
            }
        } catch (ServletException ex) {
            logger.log(Level.SEVERE, null, ex);
        }
    }

    protected String extractFileName(Part part) {
        String contentDisp = part.getHeader("content-disposition");
        String[] items = contentDisp.split(";");
        for (String s : items) {
            if (s.trim().startsWith("filename")) {
                return s.substring(s.indexOf("=") + 2, s.length() - 1);
            }
        }
        return "";
    }

}