KnockOut+TypeScript+上传图片(oos功能)以及导入Excel文件(oos功能)并回显插入

没有看过oos配置的可以参考我的另一边文章oos配置

废话不多说,上正文

一:上传图片

1.前端:

 <div class="gift-form">
     <label><span>*</span> 上传图片:</label>
     <div class="file-box" data-bind="value: image">
         <a href="javascript:;" class="a-upload">
             <input class="clickable custom-file-input" type="file" multiple="multiple" id="picture_upload" accept="image/jpeg, image/jpg, image/png"
                    data-bind="event: {change: function(){return $root.addGiftPicture()}}" >上传图片
         </a>
     </div>
 </div>

 <div class="row-info">
     <div  class="form-group" id="companyLogo" data-bind="visible: $root.isPreview">
         <label>预览</label>
     </div>
 </div>

2.TypeScript:

     /**
     * 添加礼品图片 添加
     */
    addGiftPicture = () => {
        let giftInfo = this.giftInfo();
        // @ts-ignore
        let file = $('#picture_upload')[0].files[0];//获得图片
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
            let fileName = file.name;
            let fileType = file.type;
            let fileData = reader.result as string;
            //调用方法
            CnUserGiftService.uploadGiftPicture(fileName, fileType, fileData).done(ret => {
                if (ret.uploadType) {
                    giftInfo.image = ret.logoUrl;//赋值到表单中
                    //预览回显
                    const img = new Image();
                    // @ts-ignore
                    img.src = reader.result;
                    img.className = 'company_temp_img';
                    $(".company_temp_img").remove();
                    $("#companyLogo").append(img);
                    this.isPreview(true);
                } else {
                    Notice.error('上传失败!');
                }

            });
        }

    }

ajax

    /**
     *上传图片
     */
    static uploadGiftPicture(fileName: any, fileType: any, fileData: string) {
        return Ajax.post('/cn-user/upload-gift-picture.json', {fileName, fileType, fileData});
    }

3.后台控制层:

    /**
     * 上传图片
     */
    public String uploadGiftPicture() {
        Map<String, Object> result = new HashMap<>();
        var req = readJson();
        var fileData = req.get("fileData").toString();
        var fileType = req.get("fileType").toString();
        var fileName = req.get("fileName").toString();
        var fileMap = Map.of("fileData", fileData,
                "fileType", fileType,
                "fileName", fileName);
        result = cnUserGiftManagerService.uploadGiftPicture(fileMap);
        writeJson(result);

        return null;

    }

Service:


    /**
     * 上传图片
     */
    @Override
    public Map uploadGiftPicture(Map fileMap) {
        var uploadType = false;
        var file = fileMap.get("fileData").toString();
        var fileName = fileMap.get("fileName").toString();
        if (file.startsWith("data:")) {
            file = file.substring(file.indexOf(',') + 1);
        }
        file = StringUtils.replaceEach(file, new String[]{"\n", "\r"}, new String[]{"", ""}).trim();
        byte[] bytes = Base64.getDecoder().decode(file);
        var now = LocalDateTime.now();
        var uploadRoot = "user/gift-picture/" + DateTimeFormatter.ofPattern("yyyy-MM").format(now) + "/";
        var timeKey = DateTimeFormatter.ofPattern("yyyyMMddHHmmss").format(now) + "-" + RandomStringUtils.randomAlphanumeric(6);
        var formatName = fileUtils.getImageFormatName(bytes, FORMAT_JPG);//获取图片尾缀
        var filename = "logo-" + timeKey + "." + formatName;
        uploadType = ossHelper.put(uploadRoot + filename, bytes);
        var resultMap = Map.of("uploadType", uploadType,
                "logoUrl", uploadRoot + filename);
        return resultMap;
    }

4.从OOS中读取并回显

//oos读取字节流
byte[] bytes = ossHelper.get(item.getImage());
//字节流转换为base64 传到前台
base64Img =Base64.getEncoder().encodeToString(bytes);

前台显示:

<%--图片的二种显示方式 http链接 和 oos链接--%>
<td >
    <!-- ko if: imageState == 'httpUrl' -->
    <img data-bind="attr: { src: image}" width="55px" height="55px"/>
    <!-- /ko -->
    <!-- ko if: imageState == 'oosUrl' -->
    <img data-bind="attr: { src: 'data:image/png;base64,'+imageBytes}" width="55px" height="55px"/>
    <!-- /ko -->
</td>

里面所涉及的工具类都在oos配置当中

二:导入EXCEL文件

1.前端

<div class="gift-form" id="volumeSize" data-bind="visible: $root.volumeSizeState">
    <label><span>*</span> 上传券码:</label>
    <div class="file-box">
        <a href="javascript:;" class="a-upload">
            <input type="file" id="compound_upload" data-bind="event: {change: function(){return $root.uploadGiftFile($('#compound_upload')[0].files[0])}}" accept=".xls, .xlsx">上传券码
        </a>
    </div>
</div>

2.Ts

  /**
     * 上传文件 添加
     */
    uploadGiftFile = () => {
        let giftInfo = this.giftInfo();
        // @ts-ignore
        let file = $('#compound_upload')[0].files[0];//获得文件
        if (file == null) {
            Notice.error('请上传文件!');
            return;
        }
        if (/(?:.xls|.xlsx)$/.test(file.type)) {
            Notice.error('文件格式不正确!');
            return false;
        }
        if (file.name.length > 50) {
            Notice.error('文件名命名过长!');
            return false;
        }
        const reader = new FileReader();
        reader.onload = () => {
            let fileName = file.name;
            let fileType = file.type;
            let fileData = reader.result as string;
            CnUserGiftService.uploadGiftFile(fileName, fileType, fileData).done(ret => {
                if (ret.uploadType) {
                    giftInfo.fileUrl = ret.excelUrl;//赋值到表单中
                    Notice.error('导入成功!');
                } else {
                    Notice.error('上传失败!');
                }
            })
        }
        reader.readAsDataURL(file);
    }

ajax


    /**
     *上传文件
     */

    static uploadGiftFile(fileName: any, fileType: any, fileData: string) {
        return Ajax.post('/cn-user/upload-gift-file.json', {fileName, fileType, fileData});
    }

3.后台:存入OOS
控制层


    /**
     * 上传file Excel
     */
    public String uploadGiftFile() {
        Map<String, Object> result = new HashMap<>();
        var req = readJson();
        var fileData = req.get("fileData").toString();
        var fileType = req.get("fileType").toString();
        var fileName = req.get("fileName").toString();
        var fileMap = Map.of("fileData", fileData,
                "fileType", fileType,
                "fileName", fileName);
        result = cnUserGiftManagerService.uploadGiftFile(fileMap);
        writeJson(result);

        return null;
    }

Service

    /**
     * 上传文件
     */
    @Override
    public Map uploadGiftFile(Map fileMap) {
        var uploadType = false;
        var file = fileMap.get("fileData").toString();
        var fileName = fileMap.get("fileName").toString();
        if (file.startsWith("data:")) {
            file = file.substring(file.indexOf(',') + 1);
        }
        file = StringUtils.replaceEach(file, new String[]{"\n", "\r"}, new String[]{"", ""}).trim();
        byte[] bytes = Base64.getDecoder().decode(file);
        var now = LocalDateTime.now();
        var uploadRoot = "user/upload-gift-file/" + DateTimeFormatter.ofPattern("yyyy-MM").format(now) + "/";
        var timeKey = DateTimeFormatter.ofPattern("yyyyMMddHHmmss").format(now) + "-" + RandomStringUtils.randomAlphanumeric(6);
        var formatName = fileUtils.getFileTypeByStream(bytes, fileName);//获取文件尾缀
        var filename = timeKey + "." + formatName;
        uploadType = ossHelper.put(uploadRoot + filename, bytes);
        var resultMap = Map.of("uploadType", uploadType,
                "excelUrl", uploadRoot + filename);
        return resultMap;
    }

成功存入到oos中

4.从OOS中读取EXCEL文件并插入数据库

var result = new HashMap<String, Object>();
result.put("success", 0);
// 从OOS中根据路径获得流文件
byte[] bs = ossHelper.get(newCode);
if (bs == null) {
    result.put("error", "文件上传失败!");
    writeJson(result);
    return null;
} else {
    //读取流
    InputStream stream = new ByteArrayInputStream(bs);
    XSSFWorkbook workbook = null;
    try {
        workbook = new XSSFWorkbook(stream);
    } catch (IOException e) {
        e.printStackTrace();
    }
    XSSFSheet sheet = workbook.getSheetAt(0);
    //判断条数
    int rows = sheet.getPhysicalNumberOfRows();
    if (rows > 1000) {
        result.put("error", "文档记录超过了1000条,请拆分文档!");
        writeJson(result);
        return null;
    }
    //操作excel文件
    XSSFRow row1 = sheet.getRow(0);
    if (row1 == null) {
        result.put("error", "上传的文档中没有内容!");
        writeJson(result);
        return null;
    }
    int cells = row1.getPhysicalNumberOfCells();
    //标题不能为空
    if (row1.getCell(0) != null && row1.getCell(1) != null && row1.getCell(2) != null && cells == 3) {
        //对比
        if (StringUtils.equalsIgnoreCase(row1.getCell(0).getStringCellValue(), "礼品编号")
                && StringUtils.equalsIgnoreCase(row1.getCell(1).getStringCellValue(), "兑换码")
                && StringUtils.equalsIgnoreCase(row1.getCell(2).getStringCellValue(), "过期时间")) {
            //遍历取值 进行赋值
            for (int j = 1; j < rows; j++) {
                XSSFRow row = sheet.getRow(j);
                CnUserGiftRedeemCode cnUserGiftRedeemCode = new CnUserGiftRedeemCode();
                if (row != null) {
                    if (row.getCell(0) != null) {
                        //行赋值
                        if (StringUtils.isNotBlank(fileUtils.getXSSFCellValue(row.getCell(0)))) {
                            cnUserGiftRedeemCode.setGiftId(Integer.valueOf(fileUtils.getXSSFCellValue(row.getCell(0))));
                        }
                        if (StringUtils.isNotBlank(fileUtils.getXSSFCellValue(row.getCell(1)))) {
                            cnUserGiftRedeemCode.setCode1(fileUtils.getXSSFCellValue(row.getCell(1)));
                        }
                        if (StringUtils.isNotBlank(fileUtils.getXSSFCellValue(row.getCell(2)))) {
                            //处理日期数字
                            Calendar calendar = new GregorianCalendar(1900, 0, -1);
                            Date calendars = calendar.getTime();
                            Date date = DateUtils.addDays(calendars, Integer.valueOf(fileUtils.getXSSFCellValue(row.getCell(2))));
                            Instant instant = date.toInstant();
                            ZoneId zoneId = ZoneId.systemDefault();
                            LocalDate expiresOn = instant.atZone(zoneId).toLocalDate();
                            cnUserGiftRedeemCode.setExpiresOn(expiresOn);
                        }
                    }
                }
                cnUserGiftManagerService.insertGiftRedeemCode(cnUserGiftRedeemCode);//添加礼品兑换单
            }
            result.put("success", 1);//成功结果

        } else {
            result.put("error", "标题为空或列数有误,请严格按照模板格式导入!");
            writeJson(result);
            return null;
        }
    } else {
        result.put("error", "标题名称有误,请严格按照模板格式导入!");
        writeJson(result);
        return null;
    }
    try {
        stream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

EXCEL格式:
在这里插入图片描述

三:fileUtils 文件和EXCEL文件的公共工具类(判断图片或文件的尾缀以及类型)

package com.chem.www.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.io.ByteArrayInputStream;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Slf4j
@Component
public class FileUtils {
    public static final String FORMAT_JPG = "jpg";
    public static final Map<String, String> FILE_TYPE_MAP = new HashMap<String, String>();

    static {
        FILE_TYPE_MAP.put("xls", "D0CF11E0");  //MS Word
        FILE_TYPE_MAP.put("xlsx", "504B0304");  //MS Word
    }

    /**
     * 获得图片尾缀
     */
    public String getImageFormatName(byte[] bytes, String defaultFormat) {
        try {
            var imageStream = ImageIO.createImageInputStream(new ByteArrayInputStream(bytes));
            var readerIterator = ImageIO.getImageReaders(imageStream);
            if (readerIterator.hasNext()) {
                var reader = readerIterator.next();
                var format = reader.getFormatName().toLowerCase();
                // 文件格式名参考 PNGImageReaderSpi,大体可用,只是 JPG 搞特殊,额外处理一下
                if ("jpeg".equals(format)) {
                    format = FORMAT_JPG;
                }
                return format;
            }
        } catch (Exception ignore) {
        }
        return defaultFormat;
    }


    /**
     * 获得文件尾缀
     */
    public final String getFileTypeByStream(byte[] b, String uploadName) {
        String filetypeHex = String.valueOf(getFileHexString(b));
        Iterator<Map.Entry<String, String>> entryIterator = FILE_TYPE_MAP.entrySet().iterator();
        while (entryIterator.hasNext()) {
            Map.Entry<String, String> entry = entryIterator.next();
            String fileTypeHexValue = entry.getValue();
            if (filetypeHex.toUpperCase().startsWith(fileTypeHexValue)) {
                if (entry.getKey() != null) {
                    return StringUtils.substringAfterLast(uploadName, ".");
                }
                return entry.getKey();
            }
        }
        return null;
    }


    public final String getFileHexString(byte[] b) {
        StringBuilder stringBuilder = new StringBuilder();
        if (b == null || b.length <= 0) {
            return null;
        }
        for (int i = 0; i < b.length; i++) {
            int v = b[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }


    public static String getXSSFCellValue(XSSFCell cell) {
        String cellValue = "";
        if (cell != null) {
            DecimalFormat decimalFormat = new DecimalFormat("##########.##########");
            switch (cell.getCellType()) {
                case XSSFCell.CELL_TYPE_STRING:
                    cellValue = cell.getRichStringCellValue().getString().trim();
                    break;
                case XSSFCell.CELL_TYPE_NUMERIC:
                    cellValue = decimalFormat.format(cell.getNumericCellValue());
                    break;
                case XSSFCell.CELL_TYPE_BOOLEAN:
                    cellValue = String.valueOf(cell.getBooleanCellValue()).trim();
                    break;
                case XSSFCell.CELL_TYPE_FORMULA:
                    cellValue = cell.getCellFormula();
                    break;
                default:
                    cellValue = "";
            }
        }
        return cellValue;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值