UploadUtil.java 2.62 KB
package com.lecuntao.ordering.util;

import com.xiniunet.foundation.contract.UploadTypeEnum;
import com.xiniunet.foundation.request.FileUploadRequest;
import com.xiniunet.foundation.response.FileUploadResponse;
import com.xiniunet.foundation.service.FoundationService;
import com.xiniunet.framework.security.Passport;
import com.xiniunet.framework.util.DateUtil;
import com.xiniunet.framework.util.excel.Excel;
import com.xiniunet.framework.util.excel.OldExcel;
import com.xiniunet.framework.util.excel.datatable.DataTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * Created on 2016-12-12.
 *
 * @author 小昊
 */
public class UploadUtil<T> {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    private FoundationService foundationService;

    public UploadUtil(FoundationService foundationService) {
        this.foundationService = foundationService;
    }

    public String upload(DataTable<T> table, Long tenantId, String moduleName, UploadUtil.FileType fileType, Passport passport) {

        byte[] bytes;
        if(fileType == UploadUtil.FileType.XLSX) {
            try {
                bytes = (new Excel(false, new DataTable[]{table})).getBytes();
            } catch (Exception var19) {
                this.logger.error(var19.getMessage(), var19);
                return null;
            }
        } else {
            try {
                bytes = (new OldExcel(false, new DataTable[]{table})).getBytes();
            } catch (Exception var18) {
                this.logger.error(var18.getMessage(), var18);
                return null;
            }
        }


        FileUploadRequest uploadRequest = new FileUploadRequest();
        uploadRequest.setFileExt(fileType.toString().toLowerCase());
        uploadRequest.setFileName(moduleName + "-" + DateUtil.formatDate("yyyyMMddHHmmss"));
        uploadRequest.setIsUploadByFileName(true);
        uploadRequest.setType(UploadTypeEnum.TMP);
        uploadRequest.setFileStream(bytes);

        passport.setTenantId(tenantId);

        FileUploadResponse uploadResponse = foundationService.uploadFile(uploadRequest, passport);
        return uploadResponse.getUrl();
    }

    public String upload(List<T> beanList, Long tenantId, String moduleName, Passport passport) {
        try {
            DataTable<T> dataTable = new DataTable<>(beanList);
            return this.upload(dataTable, tenantId, moduleName, UploadUtil.FileType.XLSX, passport);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
            return null;
        }
    }

    public enum FileType {
        XLS,
        XLSX;
    }
}