vue学习(五)el-upload 组件自动上传

demo直接提交类型:data带参数


<el-table-column
            label="数据"
            align="center"
            prop="data">
            <template slot-scope="scope">
              <el-upload
                ref="upload"
                :on-success="handleSuccess"//成功回调
                :on-error="handleError"//失败回调
                :before-upload="beforeUpload"//上传之前检验
                :auto-upload="true"
                :data="{cid:scope.row.id}"//传给后台的额外参数从此处是从
                action="/api/car/uploadExcel"
                class="upload-demo">
                <el-button
                  slot="trigger"
                  size="mini"
                  type="success">选择文档</el-button>
              </el-upload>
            </template>
 </el-table-column>
data() {
    return {
      fileList: []
    }
},  
methods: {
    handleError(res, file, fileList) { // 文件上传失败处理
      this.$notify.success({
        title: '失败',
        message: `文件上传失败`
      })
      this.$refs.upload.clearFiles()
    },
    handleSuccess(res, file, fileList) { // 文件上传成功处理
      this.$notify.success({
        title: '成功',
        message: `文件上传成功`
      })
      this.$refs.upload.clearFiles()
      //成功后的业务逻辑处理
    },
    beforeUpload(file) {//上传前检验
      if (!file) {
        return false
      } 
      console.log(file)
      if (/xlsx$/.test(file.name)) {
        console.log('格式正确')
        return true
      } else {
        console.log('格式错误')

        this.$message.error('请选择正确的文件上传')
        this.$refs.upload.clearFiles()
        return false
      }
    }
}

后台接参数:

  @RequestMapping(value = "/car/uploadExcel" ,method = RequestMethod.POST)
    @ResponseBody
    public Object uploadExcel(MultipartFile file, @RequestParam("cid") String cid, HttpServletRequest request) throws IOException {
        loggerFile.info("上传excel接口-----------开始" );
        loggerFile.info(cid );//这是传进来的额外的参数

        //1.获取信息
        //2.解析xlsx
        //3.插入数据库
     HashMap<String, Object> returnMap = new HashMap<String, Object>();
     
 if (file != null){
            String name = file.getOriginalFilename();
            if (name.endsWith("xlsx")) {
                //TODO excel解析 逻辑,通过excelFile.getInputStream(),处理Excel文件

                int result= 0;
                InputStream inputStream = null;
                List<List<Object>> listResult = null;
                inputStream = file.getInputStream();
                try {
                    listResult = new POIExcelUtil().getBankListByExcel(inputStream, file.getOriginalFilename());
                    //TODO 业务逻辑,循环添加
                    if (CollectionUtils.isEmpty(listResult)) {
                        returnMap.put("code","00");
                        returnMap.put("msg","文档空数据");
                    }

                    //自己的业务处理
                    //xxxxxxxxxxxxxxxxxxxxxxx

                    loggerFile.info("上传excel接口-----------操作结果"+result );
                } catch (Exception e) {
                    e.printStackTrace();
                }
                inputStream.close();

                if (result>0){
                    returnMap.put("code","00");
                    returnMap.put("num",result);
                    returnMap.put("msg","成功"+result+"条数据");
                }
            }else {
                returnMap.put("code","99");
                returnMap.put("msg","文件格式错误");
            }
        }else{
            returnMap.put("code","99");
            returnMap.put("msg","文件格式错误");
        }
        loggerFile.info("上传excel接口-----------结束" );

     return returnMap;
}

excel解析工具类

<dependencies>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.15</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>3.15</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.15</version>
        </dependency>
    </dependencies>
public class POIExcelUtil {

    private final static String excel2003L = ".xls"; // 03- 版本的excel
    private final static String excel2007U = ".xlsx"; // 07+ 版本的excel

    /**
     * 描述:根据文件后缀,自适应上传文件的版本
     *
     * @param inputStream,fileName
     * @return
     * @throws Exception
     */
    public Workbook getWorkbook(InputStream inputStream, String fileName) throws Exception {
        Workbook wb = null;
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        if (excel2003L.equals(fileType)) {
            wb = new HSSFWorkbook(inputStream); // 2003-
        } else if (excel2007U.equals(fileType)) {
            wb = new XSSFWorkbook(inputStream); // 2007+
        } else {
            throw new Exception("解析的文件格式有误!");
        }
        return wb;
    }

    /**
     * 描述:获取IO流中的数据,组装成List<List<Object>>对象
     *
     * @param inputStream,fileName
     * @return
     * @throws IOException
     */
    public List<List<Object>> getBankListByExcel(InputStream inputStream, String fileName) throws Exception {
        List<List<Object>> list = null;

        // 创建Excel工作薄
        Workbook work = this.getWorkbook(inputStream, fileName);
        if (null == work) {
            throw new Exception("创建Excel工作薄为空!");
        }
        Sheet sheet = null;
        Row row = null;
        Cell cell = null;

        list = new ArrayList<List<Object>>();
        // 遍历Excel中所有的sheet
        for (int i = 0; i < work.getNumberOfSheets(); i++) {
            sheet = work.getSheetAt(i);
            if (sheet == null) {
                continue;
            }

            // 遍历当前sheet中的所有行
            for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
                row = sheet.getRow(j);
                // 跳过空行和标题行
                if (row == null || row.getFirstCellNum() == j) {
                    continue;
                }

                // 遍历所有的列
                List<Object> li = new ArrayList<Object>();
                for (int k = row.getFirstCellNum(); k < row.getLastCellNum(); k++) {
                    cell = row.getCell(k);
                    if (cell == null) {
                        li.add("");
                        continue;
                    }

                    li.add(this.getCellValue(cell));
                }
                list.add(li);
            }
        }
        System.out.println(list);
        return list;

    }

    /**
     * 描述:对表格中数值进行格式化
     *
     * @param cell
     * @return
     */
    public Object getCellValue(Cell cell) {
        Object value = null;
        DecimalFormat df = new DecimalFormat("0"); // 格式化number String字符
        SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd"); // 日期格式化
        DecimalFormat df2 = new DecimalFormat("0.00"); // 格式化数字

        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
                value = cell.getRichStringCellValue().getString();
                break;
            case Cell.CELL_TYPE_NUMERIC:
                if ("General".equals(cell.getCellStyle().getDataFormatString())) {
                    value = df.format(cell.getNumericCellValue());
                } else if ("m/d/yy".equals(cell.getCellStyle().getDataFormatString())) {
                    value = sdf.format(cell.getDateCellValue());
                } else {
                    value = df.format(cell.getNumericCellValue());
                }
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                value = cell.getBooleanCellValue();
                break;
            case Cell.CELL_TYPE_BLANK:
                value = "";
                break;
            default:
                break;
        }
        return value;
    }

}

 

### 隐藏 Element UI 的 `el-upload` 组件 为了实现隐藏 `el-upload` 组件的功能,在 Vue 中可以通过绑定可见性属性来控制组件的显示状态。具体来说,可以利用 `v-if` 或者 `v-show` 指令配合布尔类型的变量来进行操作。 当采用 `v-if` 时,如果条件不满足,则该元素不会被渲染到 DOM 中;而使用 `v-show` 则会始终将元素保持在 DOM 上下文中,仅通过 CSS 控制其显隐[^1]。 下面是一个简单的例子展示如何基于数据属性动态切换 `el-upload` 组件的可见性: ```html <template> <div id="app"> <!-- 使用 v-if 来决定是否渲染 --> <el-upload v-if="isUploadVisible" class="upload-demo" action="https://jsonplaceholder.typicode.com/posts/" :on-preview="handlePreview" :on-remove="handleRemove" :before-remove="beforeRemove" multiple :limit="3" :on-exceed="handleExceed" :file-list="fileList"> <el-button size="small" type="primary">点击上传</el-button> <div slot="tip" class="el-upload__tip">只能上传 jpg/png 文件,且不超过500kb</div> </el-upload> <!-- 控制按钮用于改变 isUploadVisible 值 --> <button @click="toggleVisibility()">Toggle Upload Visibility</button> </div> </template> <script> export default { name: 'App', data () { return { fileList: [{name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}], isUploadVisible: true // 初始化为true表示初始状态下显示上传组件 } }, methods: { toggleVisibility(){ this.isUploadVisible = !this.isUploadVisible; }, handleRemove(file, fileList) {}, handlePreview(file) {}, handleExceed(files, fileList) {}, beforeRemove(file, fileList) {} } } </script> ``` 上述代码片段展示了如何定义一个名为 `isUploadVisible` 的响应式属性,并将其与模板中的 `v-if` 进行关联,从而达到按需显示或隐藏整个上传区域的效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我先来一碗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值