图片上传与excel的导出

图片上传

1.通过fileReader 对象将图片变成base64 和一个字符串一样使用 可以直接入库

把上传的图片的数据直接存到数据库就行

import React, { PureComponent, createRef } from "react";
class AddGoods extends PureComponent {
  fileRef = createRef();
  state = {
    img: ""
  }
  getBase64 = () => {
    const file= this.fileRef.current.files[0]
    const reader= new FileReader();
    console.log(reader)
    reader.onload= () => {
      console.log('base64转换完成')
      console.log(reader.result)
      this.setState({ img: reader.result})
    }
    reader.readAsDataURL(file)
  }

  render() {
    return (
    <div>
      <input ref={this.fileRef } type="file" />
      <button onClick={this.getBase64}>获取图片</button>
      <img src={this.state.img} alt="" />
    </div>);
  }

  componentDidMount() {}
}

export default AddGoods;

 

2. 通过formdata 服务端将文件保存到服务器 之后将图片的服务器路径入库

* 通过input file 获取图片信息

* 将文件加入到formdata对象中

* 后端会从formdata对象解析图片的数据流

* 将图片保存到服务器下(可以是自己的服务器也可以是图床) -> 产生一个找到图片的路径

* 将路径保存到数据库 返回给前端

import React, { PureComponent, createRef } from "react";
import { uploadFile } from "@/api"
class AddGoods extends PureComponent {
  fileRef = createRef();
  state = {
    img: ""
  }
  getFormData = async () => {
    const file= this.fileRef.current.files[0]
    const  form = new FormData();
    form.append("hehe",file)
    const result = await uploadFile(form) //把图片存到服务器
    //console.log(result)
    this.setState({img:`http://localhost:3000${result.path}`})
  }

  render() {
    return (
    <div>
      <input ref={this.fileRef } type="file" />
      <button onClick={this.getFormData}>获取图片</button>
      <img src={this.state.img} alt="" />
    </div>);
  }

  componentDidMount() {}
}

export default AddGoods;

Excel的导出

https://note.youdao.com/ynoteshare/index.html?id=5e08fd7ecc4d68c185b781a8496de384&type=note&_time=1654093459460https://note.youdao.com/ynoteshare/index.html?id=5e08fd7ecc4d68c185b781a8496de384&type=note&_time=1654093459460

1. 纯前端的导入导出

2. 后端提供一个下载链接

3. 通过ajax接口返回二进制数据流实现导出

方式1:纯前端方式导出

用到的不多

需要用到插件xlsx

import React, { Component } from 'react';
import  XLSX from "xlsx"
console.log(XLSX)
class ExportElsx extends Component {
  createElsx(){
    // 获取表格的dom元素
    var elt = document.getElementsByTagName('table')[0];
    console.log(elt)
    // 将表格的dom 元素转化为 excel工作薄
    var wb = XLSX.utils.table_to_book(elt, {sheet:"Sheet JS"});
    // 将工作薄导出为excel文件
    XLSX.writeFile(wb,'呵呵哒.xlsx');
  }
  state = {  }
  render() { 
    return ( 
      <div>
        <table>
          <tr>
            <td>序号</td>
            <td>名字</td>
            <td>描述</td>
            <td>呵呵</td>
          </tr>
          <tr>
            <td>1</td>
            <td>韩梅梅</td>
            <td>好看</td>
            <td>呵呵</td>
          </tr>
          <tr>
            <td>2</td>
            <td>李蕾蕾</td>
            <td>呵呵</td>
            <td>呵呵</td>
          </tr>
        </table>
        <button onClick={this.createElsx}>导出excel</button>
      </div>
     );
  }
}
 
export default ExportElsx;

方式2:后端给个链接的方式导出

直接通过后端返回来的接口通过window.open()进行打开这个链接,就会下载excel到本地,但是用户体验不好,页面会抖动一下,通过用iframe体验会更好,页面不会抖动,但是在react组件里面用不了

以下是两种方式在原生js的用法

<body>
<!-- iframe 下载测试 1-->
<button onclick='download()'>iframe</button>
<iframe name='myFrame' style="display:none;"></iframe>
<script>
  function download(){
    window.open('http://localhost:3001/admin/export','myFrame')
  }
</script>
<!-- <!-- <!-- 下载测试2 -->
 <button onclick='download()'>open下载</button>
<script>
  function download(){
    window.open('http://localhost:3001/admin/export')
  }
</script> 

在react组件里面用的时候


import React, { Component } from 'react';
import XLSX from "xlsx"
class ExportElsx extends Component {
  
  state = { }
  download = () => {
    window.open('http://localhost:3001/admin/export')
    // window.open('http://localhost:3001/kind/exportExcel','myFrame') //这是通过iframe的方法,但是在react组件里面不行
  }

  render() { 
    return ( 
      <div>
        <button onClick={this.download}>导出excel</button>
        <hr />
        通过iframe实现下载
        // <iframe name='myFrame' style="display:none;"></iframe>  会报错,在react里面不支持这样写
        <button onClick={this.download}>iframe下载</button>
      </div>
     );
  }
}
 
export default ExportElsx;

方式3: 通过ajax接口返回二进制数据流实现导出

export const uploadExcel = (data = {}) => {
  let url = "/api/admin/export";
  return  new Promise((resolve,reject) => {
    axios({
      url,
      method: "POST",
      responseType: 'arraybuffer',
    }).then((res) => {
      console.log(res)
      // 将接口请求回来的数据流转化连接
      const loadstream = window.URL.createObjectURL(new Blob([res.data]))
      // 从header里获取文件名
      const contentDisposition = res.headers['content-disposition'] || '';
      const encodedFilename = contentDisposition.split('=')[1];
      //给导出的excel取后端写的文件名字
      const filename = decodeURIComponent(encodedFilename);
      // 创建一个a标签来下载文件
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = loadstream
      link.download=filename
      document.body.appendChild(link)
      // 模拟点击按标签
      if (navigator.userAgent.indexOf('Firefox') > -1) {
        // 火狐浏览器不支持click()
        const evt = document.createEvent('MouseEvents');
        evt.initEvent('click', true, true);
        link.dispatchEvent(evt);
      } else {
        link.click();
      }
      // 释放a标签和bobel对象
      document.body.removeChild(link)
      window.URL.revokeObjectURL(loadstream) // 释放掉blob对象
      resolve({ code:0, msg: "导出成功"})
    })
  
  })
  
 
};

上面是一个处理二进制流转化成Excel的接口进行处理

在用的时候直接通过这个接口来处理数据就行

用的时候


//通过按钮来触发这个方法
 <Button key="button" type="primary" onClick={this.uploadExcel}>
              导出数据
            </Button>
// 导出数据,在组件里面定义了一个方法
  uploadExcel = async() => {
    const result = await uploadExcel({})
    const { code, msg} = result;
    if(!code) {
      message.success(msg)
    }
  }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Struts2 中,可以使用 Apache POI 库来实现导入导出图片的数据到 Excel。POI 提供了 HSSF 和 XSSF 两个 API 来操作 Excel 文件,其中 HSSF 主要用于处理 Excel 2003 及之前的版本,而 XSSF 则主要用于处理 Excel 2007 及之后的版本。 下面是一个简单的示例,演示了如何使用 POI 在 Struts2 中导出图片的数据到 Excel: 1. 首先,需要添加 Apache POI 和 Apache FileUpload 依赖。可以在 `pom.xml` 文件中添加以下内容: ``` <dependencies> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency> </dependencies> ``` 2. 创建一个 `ExportAction` 类,该类用于处理导出请求。在 `execute()` 方法中,可以使用 POI 创建一个新的工作簿,并将数据和图片添加到工作簿中。最后,将工作簿写入响应输出流,以便用户可以下载 Excel 文件。 ``` public class ExportAction extends ActionSupport { private File upload; // 上传的文件 private String uploadContentType; // 上传文件的类型 private String uploadFileName; // 上传文件的名称 public String execute() throws Exception { // 创建一个新的工作簿 Workbook workbook = new XSSFWorkbook(); // 创建一个新的工作表 Sheet sheet = workbook.createSheet("Sheet1"); // 创建表头行 Row headerRow = sheet.createRow(0); // 创建表头单元格 Cell headerCell1 = headerRow.createCell(0); headerCell1.setCellValue("ID"); Cell headerCell2 = headerRow.createCell(1); headerCell2.setCellValue("名称"); Cell headerCell3 = headerRow.createCell(2); headerCell3.setCellValue("图片"); // 读取上传的文件 InputStream input = new FileInputStream(upload); // 使用 Apache FileUpload 解析上传的文件 DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); // 遍历上传的文件项,将图片插入到工作表中 int rowIndex = 1; for (FileItem item : items) { if (!item.isFormField()) { // 获取文件名和文件内容 String fileName = item.getName(); byte[] fileContent = item.get(); // 创建单元格,将图片插入到工作表中 Row row = sheet.createRow(rowIndex++); Cell cell1 = row.createCell(0); cell1.setCellValue(rowIndex - 1); Cell cell2 = row.createCell(1); cell2.setCellValue(fileName); Cell cell3 = row.createCell(2); // 将字节数组转换为图片并插入到单元格中 int pictureIndex = workbook.addPicture(fileContent, Workbook.PICTURE_TYPE_JPEG); CreationHelper helper = workbook.getCreationHelper(); Drawing drawing = sheet.createDrawingPatriarch(); ClientAnchor anchor = helper.createClientAnchor(); anchor.setCol1(cell3.getColumnIndex()); anchor.setRow1(row.getRowNum()); Picture picture = drawing.createPicture(anchor, pictureIndex); picture.resize(1, 1); } } // 将工作簿写入响应输出流 response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment; filename=data.xlsx"); workbook.write(response.getOutputStream()); workbook.close(); return null; } // 省略 getter 和 setter 方法 } ``` 3. 创建一个 JSP 页面,该页面包含一个表单,用户可以上传包含数据和图片Excel 文件。在表单中,需要将表单的 `enctype` 属性设置为 `multipart/form-data`,以便可以上传二进制文件。 ``` <%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> <title>导入导出图片的数据到 Excel</title> </head> <body> <h1>导入导出图片的数据到 Excel</h1> <s:form action="export" method="post" enctype="multipart/form-data"> <s:file name="upload" label="上传 Excel 文件"/> <s:submit value="导出"/> </s:form> </body> </html> ``` 以上就是在 Struts2 中实现导入导出图片的数据到 Excel 的简单示例。请注意,此示例仅用于演示目的,实际应用中可能需要进行更多的错误处理和数据验证。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值