springboot整合easypoi导入带图片excel并将图片上传到FastDFS服务器

1、使用easypoi导入excel

链接: easypoi详细文档.

2、导入easypoi依赖,版本可以选择最新的

        <!--easyPoi--><dependency><groupId>cn.afterturn</groupId><artifactId>easypoi-annotation</artifactId><version>3.2.0</version></dependency><dependency><groupId>cn.afterturn</groupId><artifactId>easypoi-base</artifactId><version>3.2.0</version></dependency><dependency><groupId>cn.afterturn</groupId><artifactId>easypoi-web</artifactId><version>3.2.0</version></dependency>

3、配置FastDFSUploadUtils上传工具

FastDFSUploadUtils

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.exception.FdfsUnsupportStorePathException;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;import java.io.IOException;/*** FastDFS文件上传功能*/
@Component
@EnableConfigurationProperties(UploadConfig.class)
@Slf4j
public class FastDFSUploadUtils {@Autowiredprivate FastFileStorageClient storageClient;@Autowiredprivate UploadConfig uploadConfig;/*** 上传图片返回图片地址* @param file* @return*/public String uploadImage(MultipartFile file) {try {// 上传到FastDFS// 获取扩展名String extension = StringUtil.substringAfterLast(file.getOriginalFilename(), ".");// 上传StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), extension, null);// 返回路径return uploadConfig.getBaseUrl() + storePath.getFullPath();} catch (IOException e) {log.error("【File upload】File upload fail!....{}", e);throw new RuntimeException("【File upload】File upload fail!" + e.getMessage());}}
}

UploadConfig

@Component
@ConfigurationProperties(prefix = "fdfs-upload")
@Data
public class UploadConfig {private String baseUrl;private List<String> allowTypes;
}

配置文件

#fastdfs图片存储服务器配置
fdfs:so-timeout: 2500connect-timeout: 600thumb-image:width: 100height: 100tracker-list:- 10.217.4.219:22122pool:jmx-enabled: false
fdfs-upload:base-url: http://FastDFS配置的域名/allow-types:- image/jpeg- image/png- image/bmp- image/gif- audio/mpeg

4、easypoi导入excel带图片方法

1、 新建实体类

@Getter
@Setter
public class FoodInfoImport {@Excel(name = "名称")private String name;@Excel(name = "可食部分",replace = {"null_0"})private Double ksbf;@Excel(name = "热量",replace = {"null_0"})private Double hot;@Excel(name = "水分",replace = {"null_0"})private Double water;@Excel(name = "蛋白质",replace = {"null_0"})private Double dbz;@Excel(name = "脂肪",replace = {"null_0"})private Double zf;@Excel(name = "膳食纤维",replace = {"null_0"})private Double sfqw;@Excel(name = "碳水化物",replace = {"null_0"})private Double dshw;//type=2 将excel列的内容设置图片 ,默认为1文本@Excel(name = "图片",type = 2,width = 10,savePath = "/home/static/food_img")private String foodImg;
}
注意 图片需要将type设置为2,并且可以设置图片保存路径 savagePath,默认保存路径为/excel/upload/excelUpload,首先会在此路径下保存图片,然后将该路径下的文件上传到FastDFS中

2、上传excel接口

import org.apache.poi.util.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.mock.web.MockMultipartFile;@Autowired
private FastDFSUploadUtils uploadUtils;@PostMapping("/food/import")
@ApiOperation(value = "批量导入Excel")
public String save(@RequestParam("foots") MultipartFile foots) throws Exception {ImportParams params = new ImportParams();List<FoodInfoImport> result = ExcelImportUtil.importExcel(foots.getInputStream(),FoodInfoImport.class, params);//将图片上传到FastDFS并且将地址保存result.forEach(food->{if(StringUtil.isNotEmpty(food.getFoodImg())){try {File file = new File(food.getFoodImg());FileInputStream fileInputStream = new FileInputStream(file);MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain",IOUtils.toByteArray(fileInputStream));String imgUrl = uploadUtils.uploadFile(multipartFile);food.setFoodImg(imgUrl);} catch (Exception e) {e.printStackTrace();}}});List<FoodInfo> info = result.stream().map(foodDc::invoke).collect(Collectors.toList());//业务层保存数据service.saveBatch(info);return "success";}

3、分析代码

重点是需要将读取出来的file转化为 MultipartFile,然后进行上传到FastDFS上

MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain",IOUtils.toByteArray(fileInputStream));

可知MultipartFileinterface,并没有直接可以创建实例

/*** A representation of an uploaded file received in a multipart request.** <p>The file contents are either stored in memory or temporarily on disk.* In either case, the user is responsible for copying file contents to a* session-level or persistent store as and if desired. The temporary storage* will be cleared at the end of request processing.** @author Juergen Hoeller* @author Trevor D. Cook* @since 29.09.2003* @see org.springframework.web.multipart.MultipartHttpServletRequest* @see org.springframework.web.multipart.MultipartResolver*/
public interface MultipartFile extends InputStreamSource {}

通过继承的实例可以创建 MockMultipartFile,来实现MultipartFile接口,通过源码可以发现

/*** Mock implementation of the {@link org.springframework.web.multipart.MultipartFile}* interface.** <p>Useful in conjunction with a {@link MockMultipartHttpServletRequest}* for testing application controllers that access multipart uploads.** @author Juergen Hoeller* @author Eric Crampton* @since 2.0* @see MockMultipartHttpServletRequest*/
public class MockMultipartFile implements MultipartFile {private final String name;private String originalFilename;@Nullableprivate String contentType;private final byte[] content;/*** Create a new MockMultipartFile with the given content.* @param name the name of the file* @param content the content of the file*/public MockMultipartFile(String name, @Nullable byte[] content) {this(name, "", null, content);}/*** Create a new MockMultipartFile with the given content.* @param name the name of the file* @param contentStream the content of the file as stream* @throws IOException if reading from the stream failed*/public MockMultipartFile(String name, InputStream contentStream) throws IOException {this(name, "", null, FileCopyUtils.copyToByteArray(contentStream));}/*** Create a new MockMultipartFile with the given content.* @param name the name of the file* @param originalFilename the original filename (as on the client's machine)* @param contentType the content type (if known)* @param content the content of the file*/public MockMultipartFile(String name, @Nullable String originalFilename, @Nullable String contentType, @Nullable byte[] content) {Assert.hasLength(name, "Name must not be null");this.name = name;this.originalFilename = (originalFilename != null ? originalFilename : "");this.contentType = contentType;this.content = (content != null ? content : new byte[0]);}
}

以上就是springboot+easypoi上传excel带图片的并上传到FastDFS服务器功能以及实现

springboot整合easypoi导入带图片excel并将图片上传到FastDFS服务器相关推荐

  1. SpringBoot整合腾讯云COS对象存储实现文件上传

    企业级项目开发中都会有文件.图片.视频等文件上传并能够访问的场景,对于初学者Demo可能会直接存储在应用服务器上:对于传统项目可能会单独搭建FastDFS.MinIO等文件服务来实现存储,这种方案可能 ...

  2. 百度ueditor富文本--图片保存路径的配置以及上传到远程服务器

    我们在上篇文章中学习了  上传图片的配置: 百度ueditor富文本--配置图片上传 在文章的最后 讲到  ueditor 默认设置的 保存图片的 路径 是相对路径,项目相关的. 保存的图片会放在to ...

  3. 【SpringBoot】37、SpringBoot整合EasyPoi自定义字典导出Excel

    前面我们介绍了 SpringBoot 中使用 JeecgBoot 的 Autopoi 导出 Excel,其实 Autopoi 的底层也是 EasyPoi,对于 Excel 的导入/导出也是非常方便的. ...

  4. php 表格导入excel插件,BootStrap Fileinput插件和表格插件相结合实现导入Excel数据的文件上传、预览、提交的步骤...

    这篇文章主要介绍了BootStrap Fileinput插件和Bootstrap table表格插件相结合实现文件上传.预览.提交的导入Excel数据操作步骤,需要的朋友可以参考下 bootstrap ...

  5. 上传图片到linux返回url,Springboot 将前端传递的图片上传至Linux服务器并返回图片的url(附源码)...

    问题由来: 用户个人信息需要添加头像功能 当前端程序是微信小程序时,前端将直接将图片 url 传送至服务端 但是当前端是 Web 页面时,前端传递的参数是一张图片,服务端需要将图片保存至 Linux ...

  6. Nginx、图片上传、FastDFS

    学习目标 使用域名访问本地项目 Nginx 图片上传 FastDFS实现图片上传 1.使用域名访问本地项目 1.1.统一环境 我们现在访问页面使用的是:http://localhost:8080 有没 ...

  7. # iOS 相册图片多选以及类似微信获取相册图片并使用AFN框架上传至服务器

    iOS 相册图片多选以及类似微信获取相册图片并使用AFN框架上传至服务器 做APP基本上都是需要从系统的相册当中获取一张或多张图片.那怎么做呢?下面我就带你来实现这个内容,第一次写. 我只是记录一下. ...

  8. excel文件导出并上传到服务器上

    (个人业务,将需要导出的数据,写到excel文件中并上传到相对应的服务器上) ```java//excel标题String[] title = {"用户名(非必填)", " ...

  9. moba上传文件到服务器,图片上传到远程服务器上的方法

    图片上传到远程服务器上的方法 内容精选 换一换 将文件上传至Windows云服务器一般会采用MSTSC远程桌面连接的方式.本节为您介绍本地Windows计算机通过远程桌面连接,上传文件至Windows ...

最新文章

  1. ggplot2包绘基因差异表达点图
  2. 并发异步处理队列 .NET 4.5+
  3. 判断mos管好坏_想要保护电动车控制器,推荐这款STP75NF75高压MOS管
  4. jQueru中数据交换格式XML和JSON对比
  5. VS生产dll把双目追踪四个圆点计算的物体位姿给unity,在unity中实时变化
  6. 虚拟打印机可以设置默认保存路径吗
  7. revit二次开发概念_Revit二次开发那些事儿
  8. Node+puppeteer学习笔记(三)--API问题解决--切换frame和iframe框
  9. 【你问我答】不包装简历是不是面试机会都没有?
  10. 机器学习老中医:利用学习曲线诊断模型的偏差和方差
  11. 何为数码相机EXIF信息的等效焦距
  12. 第8节 Kali及其他Linux系统软件分类及安装
  13. md+邮件服务器+334错误,邮件发送,无尽的501错误。TCP发送邮件解决方案
  14. 数字孪生技术助力高炉数字化建设的可行性
  15. Java面试复习与笔记
  16. 20200323ziji
  17. 为什么采用实时操作系统?
  18. 2022 极术通讯—AR的元宇宙
  19. Scratch少儿编程精品课3六六的旅行
  20. 机器视觉开源代码合集

热门文章

  1. AccordionControl 左侧导航
  2. 55——SPNet: A novel deep neural network for retinal vessel segmentation basedon shared decoder and p
  3. 天正对应cad版本_天正建筑找不到可用的cad版本怎么办?天正建筑找不到可用的cad版本解决办法...
  4. peal php,python基础--列表
  5. 2018年下半年网络工程师考试试题分析(3)
  6. 根据详细地址获取经纬度
  7. 《量子物理史话》主线 - 光是什么?(未完)
  8. SQL语句中:UNION与UNION ALL的区别
  9. 视频合并分割软件如何剪切视频
  10. uve-elementUI-temple模板添加动态路由