com.fjn.helper.common.io.file.upload.FileUploadHelper.java Source code

Java tutorial

Introduction

Here is the source code for com.fjn.helper.common.io.file.upload.FileUploadHelper.java

Source

/*
 *
 *  Copyright 2018 FJN Corp.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *  Author                        Date                       Issue
 *  fs1194361820@163.com          2015-01-01                 Initial Version
 *
 */

package com.fjn.helper.common.io.file.upload;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.fjn.helper.common.util.EncodingUtil.UTF8;
import static com.fjn.helper.common.util.EncodingUtil.encodingCheck;

import com.fjn.helper.common.exception.FileDirFaultException;
import com.fjn.helper.common.io.file.common.FileNameBuilder;
import com.fjn.helper.common.io.file.common.FileUtil;
import com.fjn.helper.common.util.EncodingUtil;
import com.fjn.helper.common.util.StringUtil;

public class FileUploadHelper {

    private static int defaultSizeThreshold = 1024 * 1024 * 1024;
    private static final String defaultEncoding = UTF8;
    private static final Logger log = LoggerFactory.getLogger(FileUploadHelper.class);

    /**
     * ?
     * @param request
     * @return
     */
    public static boolean isFileUploadRequest(HttpServletRequest request) {
        return ServletFileUpload.isMultipartContent(request);
    }

    /**
     * ?request?fireDir?request.setAttribute(fieldName, value)?
     *
     * @param request 
     * @param fileDir 
     * @param maxSize ?
     * @param isFileNameBaseTime ????
     * @param encoding
     */
    public static FileUploadRequestParamterContext upload(HttpServletRequest request, String fileDir, int maxSize,
            boolean isFileNameBaseTime, String encoding) {
        // ?
        if (!isFileUploadRequest(request))
            return null;
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // dir??
        File dir = new File(fileDir);
        if (!dir.exists()) {
            if (dir.mkdirs()) {
                throw new FileDirFaultException(dir);
            }
            ;
        }
        if (maxSize > 0) {
            factory.setSizeThreshold(maxSize);
        }

        factory.setRepository(dir);

        // ?
        ServletFileUpload fileUploader = new ServletFileUpload(factory);
        fileUploader.setHeaderEncoding(encodingCheck(encoding) ? encoding : defaultEncoding);
        String realEncoding = fileUploader.getHeaderEncoding();

        List<FileItem> items = null;
        try {
            items = fileUploader.parseRequest(request);
        } catch (FileUploadException e1) {
            e1.printStackTrace();
        }
        if (items == null)
            return null;

        FileUploadRequestParamterContext context = new FileUploadRequestParamterContext();
        Map<String, List<File>> fileMap = context.getFileMap();
        Map<String, List<String>> fieldMap = context.getFormFieldMap();

        FileItem fileItem = null;
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            fileItem = iter.next();
            String fieldName = fileItem.getFieldName();
            if (fileItem.isFormField()) {
                List<String> values = fieldMap.get(fieldName);
                if (values == null) {
                    values = new ArrayList<String>();
                    fieldMap.put(fieldName, values);
                }
                String value = null;
                try {
                    value = fileItem.getString(realEncoding);
                } catch (UnsupportedEncodingException e) {
                    value = "";
                    e.printStackTrace();
                }
                values.add(value);
                log.info("param:\t" + fieldName + "=" + value);
            } else {
                List<File> files = fileMap.get(fieldName);
                if (files == null) {
                    files = new ArrayList<File>();
                    fileMap.put(fieldName, files);
                }

                String clientFileName = fileItem.getName();// ???
                if (StringUtil.isNull(clientFileName)) { // 
                    continue;
                }
                String realFileName = FileUtil.getRealFileName(clientFileName);
                String newFileName = null;
                if (isFileNameBaseTime) {
                    newFileName = new FileNameBuilder().build(realFileName);
                } else {
                    newFileName = realFileName;
                }
                File tempfile = new File(dir, newFileName);
                try {
                    fileItem.write(tempfile);
                    log.info("???\t" + newFileName);
                    files.add(tempfile);
                } catch (Exception e) {
                    continue;
                }
            }
        }

        return null;
    }

    /**
     * ???
     * @param request 
     * @param encoding ?????character?{@link EncodingUtil}
     * @return ?
     * @see {@link #getFormFiledItmes(HttpServletRequest, String)}
     * @see {@link ServletFileUpload#parseParameterMap(HttpServletRequest)}
     */
    public static Map<String, List<FileItem>> getFormFiledToFileItemMap(HttpServletRequest request,
            String encoding) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(defaultSizeThreshold);
        ServletFileUpload fileUploader = new ServletFileUpload(factory);
        fileUploader.setHeaderEncoding(encodingCheck(encoding) ? encoding : defaultEncoding);
        Map<String, List<FileItem>> fieldItemMap = null;
        try {
            // formfield??FileItem
            fieldItemMap = fileUploader.parseParameterMap(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        return fieldItemMap;
    }

    /**
     * ???
     * @param request 
     * @param encoding encoding ?????character?{@link EncodingUtil}
     * @return ?
     * @see {@link #getFormFiledToFileItemMap(HttpServletRequest, String) }
     * @see {@link ServletFileUpload#parseRequest(HttpServletRequest)}
     */
    public static List<FileItem> getFormFiledItmes(HttpServletRequest request, String encoding) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(defaultSizeThreshold);
        ServletFileUpload fileUploader = new ServletFileUpload(factory);
        fileUploader.setHeaderEncoding(encodingCheck(encoding) ? encoding : defaultEncoding);
        List<FileItem> fileItems = null;
        try {
            // form?
            fileItems = fileUploader.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        return fileItems;
    }

}