com.eryansky.common.web.servlet.kindeditor.FileUploadServlet.java Source code

Java tutorial

Introduction

Here is the source code for com.eryansky.common.web.servlet.kindeditor.FileUploadServlet.java

Source

/**
 *  Copyright (c) 2012-2014 http://www.eryansky.com
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.eryansky.common.web.servlet.kindeditor;

import com.eryansky.common.utils.StringUtils;
import com.eryansky.common.utils.io.FileUtil;
import com.eryansky.common.web.utils.ServletUtils;
import com.google.common.collect.Maps;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * kindeditor.
 * @author &Eryan eryanwcp@gmail.com
 * @date 2013-6-2 ?3:51:43 
 * @version 1.0
 */
public class FileUploadServlet extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    //???
    protected HashMap<String, String> extMap = new HashMap<String, String>();
    //?
    protected long maxSize = 1000000;
    //?
    protected String configPath = "attached/";

    public void init() throws ServletException {
        extMap.put("image", "gif,jpg,jpeg,png,bmp");
        extMap.put("flash", "swf,flv");
        extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
        extMap.put("file", "doc,docx,xls,xlsx,pdf,ppt,htm,html,txt,zip,rar,gz,bz2");
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String dirName = request.getParameter("dir");
        if (dirName == null) {
            dirName = "image";
        }

        //?
        String uploadPath = getInitParameter("UPLOAD_PATH");
        if (StringUtils.isNotBlank(uploadPath)) {
            configPath = uploadPath;
        }

        if ("image".equals(dirName)) {

            //?
            Long size = Long.parseLong(getInitParameter("Img_MAX_SIZE"));
            if (size != null) {
                maxSize = size;
            }

            //(?gif, jpg, jpeg, png, bmp)
            String type = getInitParameter("Img_YPES");
            if (StringUtils.isNotBlank(type)) {
                extMap.put("image", type);
            }

        } else {
            //?
            Long size = Long.parseLong(getInitParameter("File_MAX_SIZE"));
            if (size != null) {
                maxSize = size;
            }

            if ("file".equals(dirName)) {
                //(doc, xls, ppt, pdf, txt, rar, zip)
                String type = getInitParameter("File_TYPES");
                if (StringUtils.isNotBlank(type)) {
                    extMap.put("file", type);
                }
            }
        }

        if (StringUtils.isBlank(configPath)) {
            ServletUtils.renderText(getError("?!"), response);
            return;
        }

        //?
        String savePath = this.getServletContext().getRealPath("/") + configPath;

        //?URL
        String saveUrl = request.getContextPath() + "/" + configPath;

        if (!ServletFileUpload.isMultipartContent(request)) {
            ServletUtils.renderText(getError(""), response);
            return;
        }
        //
        File uploadDir = new File(savePath);
        if (!uploadDir.isDirectory()) {
            FileUtil.createDirectory(uploadDir.getPath());
            //         ServletUtils.rendText(getError("?"), response);
            //         return;
        }
        //??
        if (!uploadDir.canWrite()) {
            ServletUtils.renderText(getError("??"), response);
            return;
        }

        if (!extMap.containsKey(dirName)) {
            ServletUtils.renderText(getError("???"), response);
            return;
        }
        //
        savePath += dirName + "/";
        saveUrl += dirName + "/";
        File saveDirFile = new File(savePath);
        if (!saveDirFile.exists()) {
            saveDirFile.mkdirs();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String ymd = sdf.format(new Date());
        savePath += ymd + "/";
        saveUrl += ymd + "/";
        File dirFile = new File(savePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");

        try {
            List items = upload.parseRequest(request);
            Iterator itr = items.iterator();
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();
                String fileName = item.getName();
                long fileSize = item.getSize();
                if (!item.isFormField()) {
                    //?
                    if (item.getSize() > maxSize) {
                        ServletUtils.renderText(getError("??"), response);
                        return;
                    }
                    //??
                    String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                    if (!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)) {
                        ServletUtils
                                .renderText(getError("??????\n??"
                                        + extMap.get(dirName) + "?"), response);
                        return;
                    }

                    SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                    String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
                    try {
                        File uploadedFile = new File(savePath, newFileName);
                        item.write(uploadedFile);
                    } catch (Exception e) {
                        ServletUtils.renderText(getError(""), response);
                        return;
                    }

                    Map<String, Object> obj = Maps.newHashMap();
                    obj.put("error", 0);
                    obj.put("url", saveUrl + newFileName);
                    ServletUtils.renderText(obj, response);
                }
            }
        } catch (FileUploadException e1) {
            e1.printStackTrace();
        }

    }

    private Map<String, Object> getError(String message) {
        Map<String, Object> obj = Maps.newHashMap();
        obj.put("error", 1);
        obj.put("message", message);
        return obj;
    }
}