All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.luues.util.upload.ue.UEUploader Maven / Gradle / Ivy

There is a newer version: 1.3.0.5.RELEASE
Show newest version
package com.luues.util.upload.ue;

import com.luues.util.date.DateTime;
import com.luues.util.uuid.JUUID;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import sun.misc.BASE64Decoder;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.*;

/**
 * UEditor文件上传辅助类
 */
public class UEUploader {

    private UEFileInfo ueFileInfo;

    public UEUploader() {
        if(null == ueFileInfo){
            ueFileInfo = new UEFileInfo();
            ueFileInfo.setErrorInfo(new HashMap());
            ueFileInfo.getErrorInfo().putAll(UEError.getAll());
        }

    }

    public UEFileInfo upload(HttpServletRequest request) {
        DiskFileItemFactory fac = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(fac);
        upload.setHeaderEncoding("utf-8");
        try {
            upload.parseRequest(request);
        } catch (FileUploadException ex) {
            System.out.println(ex.getMessage());
        }
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart) {
            ueFileInfo.setState(UEError.NOFILE.getValue());
            return null;
        }
        DiskFileItemFactory dff = new DiskFileItemFactory();
        try {
            ServletFileUpload sfu = new ServletFileUpload(dff);
            sfu.setHeaderEncoding("utf-8");
            FileItemIterator fii = sfu.getItemIterator(request);
            while (fii.hasNext()) {
                FileItemStream fis = fii.next();
                if (!fis.isFormField()) {
                    ueFileInfo.setOriginalName(fis.getName().substring(fis.getName().lastIndexOf(System.getProperty("file.separator")) + 1));
                    if (!checkFileType(ueFileInfo.getOriginalName())) {
                        ueFileInfo.setState(UEError.TYPE.getValue());
                        continue;
                    }
                    setFileName();
                    ueFileInfo.setType(getFileExt(ueFileInfo.getFileName()));
                    ueFileInfo.setUrl(ueFileInfo.getSavePath() + "/" + ueFileInfo.getFileName());
                    BufferedInputStream in = new BufferedInputStream(fis.openStream());
                    File file = new File(this.getPhysicalPath(request, ueFileInfo.getUrl()));
                    FileOutputStream out = new FileOutputStream(file);
                    BufferedOutputStream output = new BufferedOutputStream(out);
                    Streams.copy(in, output, true);
                    ueFileInfo.setState(UEError.SUCCESS.getValue());
                    ueFileInfo.setSize(file.length());
                    //UE中只会处理单张上传,完成后即退出
                    break;
                } else {
                    String fname = fis.getFieldName();
                    //只处理title,其余表单请自行处理
                    if (!fname.equals("pictitle")) {
                        continue;
                    }
                    BufferedInputStream in = new BufferedInputStream(fis.openStream());
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    StringBuffer result = new StringBuffer();
                    while (reader.ready()) {
                        result.append((char) reader.read());
                    }
                    ueFileInfo.setTitle(new String(result.toString().getBytes(), "utf-8"));
                    reader.close();

                }
            }
        } catch (FileUploadBase.SizeLimitExceededException e) {
            ueFileInfo.setState(UEError.SIZE.getValue());
        } catch (FileUploadBase.InvalidContentTypeException e) {
            ueFileInfo.setState(UEError.ENTYPE.getValue());
        } catch (FileUploadException e) {
            ueFileInfo.setState(UEError.REQUEST.getValue());
        } catch (Exception e) {
            ueFileInfo.setState(UEError.UNKNOWN.getValue());
        }
        return ueFileInfo;
    }

    /**
     * 接受并保存以base64格式上传的文件
     *
     * @param fieldName
     */
    public UEFileInfo uploadBase64(HttpServletRequest request, String fieldName) {
        String savePath = this.getFolder(request, ueFileInfo.getSavePath());
        String base64Data = request.getParameter(fieldName);
        ueFileInfo.setFileName(JUUID.getUUID() + ".png");
        ueFileInfo.setUrl(savePath + "/" + ueFileInfo.getFileName());
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            File outFile = new File(this.getPhysicalPath(request, ueFileInfo.getUrl()));
            OutputStream ro = new FileOutputStream(outFile);
            byte[] b = decoder.decodeBuffer(base64Data);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            ro.write(b);
            ro.flush();
            ro.close();
            ueFileInfo.setState(UEError.SUCCESS.getValue());
        } catch (Exception e) {
            ueFileInfo.setState(UEError.IO.getValue());
        }
        return ueFileInfo;
    }

    /**
     * 文件类型判断
     *
     * @param fileName
     * @return
     */
    protected boolean checkFileType(String fileName) {
        Iterator type = Arrays.asList(ueFileInfo.getAllowFiles()).iterator();
        while (type.hasNext()) {
            String ext = type.next();
            if (fileName.toLowerCase().endsWith(ext)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取文件扩展名
     *
     * @return string
     */
    protected String getFileExt(String fileName) {
        return fileName.substring(fileName.lastIndexOf("."));
    }

    /**
     * 依据原始文件名生成新文件名
     *
     * @return
     */
    protected void setFileName() {
        Random random = new Random();
        ueFileInfo.setFileName(random.nextInt(10000) + System.currentTimeMillis() + this.getFileExt(ueFileInfo.getOriginalName()));
    }

    /**
     * 根据字符串创建本地目录 并按照日期建立子目录返回
     *
     * @param path
     * @return
     */
    protected String getFolder(HttpServletRequest request, String path) {
        path += "/" + DateTime.format("yyyyMMdd");
        File dir = new File(this.getPhysicalPath(request, path));
        if (!dir.exists()) {
            try {
                dir.mkdirs();
            } catch (Exception e) {
                ueFileInfo.setState(UEError.DIR.getValue());
                return "";
            }
        }
        return path;
    }

    /**
     * 根据传入的虚拟路径获取物理路径
     *
     * @param path
     * @return
     */
    protected String getPhysicalPath(HttpServletRequest request, String path) {
        String servletPath = request.getServletPath();
        String realPath = request.getSession().getServletContext()
                .getRealPath(servletPath);
        return new File(realPath).getParent() + "/" + path;
    }

}





© 2015 - 2024 Weber Informatics LLC | Privacy Policy