前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >导入excel时,前端传加密文件流,后端拿到后生成excel

导入excel时,前端传加密文件流,后端拿到后生成excel

作者头像
发布2021-04-02 07:55:25
1.7K0
发布2021-04-02 07:55:25
举报
文章被收录于专栏:后端JavaEE后端JavaEE

本文只有部分方法

一、概述

两种方式: 1.前端使用组件传递FileItem对象给后端

2.前端传递文件流给后端(本文使用的)

在这里插入图片描述
在这里插入图片描述

两种方式都是,浏览器(前端)点击导入按钮,弹出文件选择框,点击文件选择打开,此时前端拿到该文件的文件流(或者fileItem对象),作为参数传递给后端。 后端拿到参数,以字符串分割的方式或者fileItem类里面的方法,拿到后端需要的文件流以及文件名。

二、后端

先拿到前端传递的fileStream参数,用split将参数分割为,名称和文件流

代码语言:javascript
复制
//将得到的字符串以逗号分割去掉无用信息,第一个是文件名称,第二个是经过base64加密的文件流:fileStream2
        String[] split = fileStream.split(",");
        String fileName = split[0];
        String fileStream2 = split[2];

使用第二种方式:传递加密前端文件流时,需要先在本地生成文件,在解析拿到后端的文件流,进行录入操作 注:前端和后端的文件流不同

代码语言:javascript
复制
//定义生成文件的名称
        String randomFileName = RandomStringUtils.randomNumeric(3)+System.currentTimeMillis();
        //文件路径为本地桌面
        String filePath = getPath()+"\\"+randomFileName+".xls";
        //调用generateExcel方法,根据fileStream2文件流和生成路径filePath,生成文件
        InputStream inputStream = null;
        try {
            //将前端传的流,和指定的文件地址,在filePath位置生成文件
            generateExcel(fileStream2,filePath);
            inputStream = new FileInputStream(new File(filePath));
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            throw new StatusException(Messages.getString("systemMsg.noShareFile"));
        }

        Workbook wk = null;
        FileOutputStream fout = null;
        try {
            //判断excel的版本是2003还是2007,还是不是excel
			if (ExcelUtil.isExcel2003(fileName)) {
				wk = new HSSFWorkbook(inputStream);
			} else if (ExcelUtil.isExcel2007(fileName)){
				wk = new XSSFWorkbook(inputStream);
			}
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            throw new StatusException(Messages.getString("systemMsg.noShareFile"));
        }

拿到前端的base64加密的文件流,自己指定生成文件位置

代码语言:javascript
复制
/**
     * Base64解码并生成excel文件
     * @param fileStr  文件base64
     * @param filePath 输出路径
     */
    public static void generateExcel(String fileStr, String filePath) throws Exception {
        Log log = LogFactory.getLog(ImportOrg.class);
        byte[] bytes;
        OutputStream out = null;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
        // 解码并处理数据
            bytes = decoder.decodeBuffer(fileStr);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {
                    bytes[i] += 256;
                }
            }
            // 生成图片文件
            out = new FileOutputStream(filePath);
            out.write(bytes);
            out.flush();
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            throw new StatusException(Response.Status.INTERNAL_SERVER_ERROR, Messages.getString("slw.failed"));
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                    throw new StatusException(Messages.getString("systemMsg.noShareFile"));
                }
            }
        }

    }
    //得到本地桌面路径(用于生成导入的excel)
    public static String getPath() {
        FileSystemView view = FileSystemView.getFileSystemView();
        File file = view.getHomeDirectory();
        return file.getPath();
    }
    //删除刚生成的文件
    public static void delFile(String filePath){
        File file = new File(filePath);
        file.delete();
    }

三、前端

代码语言:javascript
复制
<input
              type="file"
              ref="file1"
              id="file1"
              @change="inclusionFile"
              style="
                width: 74px;
                border-radius: 2px;
                margin-left: 10px;
                margin-top: 2px;
                display: none;
              "
            />
            <button
              :size="'sm'" 
              :icon="'fa-user'"
              :type="'default'"
              @click="$refs.file1.click()"
            >
              导入
            </button>
代码语言:javascript
复制
// 导入功能
    inclusionFile(upfile) {
      var that = this;
      const file = upfile.target.files[0];
      const reader = new FileReader();
      // 读取文件内容,以base64格式返回结果
      const fileData = reader.readAsDataURL(file);
      console.log(file);
      if (this.isExcel(file.name)) {
        reader.onload = async () => {
          this.fileData = reader.result;
          let response = await that.$http.upload.uploadFile({
            fileStream: `${file.name},${this.fileData}`,
          });
          if (response) {
            //  console.log(that.csstree)
            that.csstree.find("sOrgtree").init();
            that.query();
            response.result == "0"
              ? $css.tip(response.msg)
              : $css.confirm(response.msg);
          }
         
        };
      } else {
        this.$dialog.alert("文件格式不正确!");
      }
    },
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-03-31 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、概述
  • 二、后端
  • 三、前端
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档