当前位置:   article > 正文

Springboot 返回文件给前端_springboot返回文件流给前端

springboot返回文件流给前端

首先导入数据到excel中

  1. package com.ds.crawler.search.service.thirdParty;
  2. import java.io.FileNotFoundException;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. import java.util.Date;
  6. import java.util.List;
  7. import com.ds.model.CrawlerModel;
  8. import com.ds.model.CrawlerResultModel;
  9. import org.apache.poi.ss.usermodel.Cell;
  10. import org.apache.poi.ss.usermodel.Row;
  11. import org.apache.poi.ss.usermodel.Sheet;
  12. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  13. public class ExportToExcel {
  14. public static Boolean exportToExcel(List<CrawlerModel> products){
  15. // 创建工作簿对象
  16. XSSFWorkbook workbook = new XSSFWorkbook();
  17. // 创建工作表对象
  18. Sheet sheet = workbook.createSheet("products");
  19. // 创建表头行
  20. Row header = sheet.createRow(0);
  21. header.createCell(0).setCellValue("ID");
  22. header.createCell(1).setCellValue("site");
  23. header.createCell(2).setCellValue("name");
  24. header.createCell(3).setCellValue("price");
  25. header.createCell(4).setCellValue("unit");
  26. header.createCell(5).setCellValue("time");
  27. header.createCell(6).setCellValue("source");
  28. header.createCell(7).setCellValue("type");
  29. header.createCell(8).setCellValue("size");
  30. header.createCell(9).setCellValue("color");
  31. header.createCell(10).setCellValue("img");
  32. header.createCell(11).setCellValue("material");
  33. header.createCell(12).setCellValue("rank");
  34. // 填充数据
  35. int rowNum = 1;
  36. for (CrawlerModel product : products) {
  37. Row row = sheet.createRow(rowNum);
  38. row.createCell(0).setCellValue(rowNum);
  39. row.createCell(1).setCellValue(product.getSite()==null?"":product.getSite());
  40. row.createCell(2).setCellValue(product.getName()==null?"":product.getName());
  41. row.createCell(3).setCellValue(((product.getPrice()==null?"":product.getPrice().toString())));
  42. row.createCell(4).setCellValue(product.getUnit()==null?"":product.getUnit());
  43. row.createCell(5).setCellValue(product.getTime()==null?"":product.getTime());
  44. row.createCell(6).setCellValue(product.getSource()==null?"":product.getSource());
  45. row.createCell(7).setCellValue(product.getType()==null?"":product.getType());
  46. row.createCell(8).setCellValue(product.getSize()==null?"":product.getSize().toString());
  47. row.createCell(9).setCellValue(product.getColor()==null?"":product.getColor().toString());
  48. row.createCell(10).setCellValue(product.getImg()==null?"":product.getImg().toString());
  49. row.createCell(11).setCellValue(product.getMaterial()==null?"":product.getMaterial());
  50. row.createCell(12).setCellValue(product.getRank()==null?"":product.getRank().toString());
  51. rowNum++;
  52. }
  53. // 将数据写入Excel文件
  54. FileOutputStream outputStream = null;
  55. try {
  56. outputStream = new FileOutputStream("products.xlsx");
  57. workbook.write(outputStream);
  58. workbook.close();
  59. outputStream.close();
  60. return true;
  61. } catch (IOException e) {
  62. throw new RuntimeException(e);
  63. }
  64. }
  65. }

之后就会看到到处的excel文件了:

创建接口返回文件到前端: 

  1. package com.ds.crawler.search.controller;
  2. import com.ds.common.exception.BizCodeEnume;
  3. import com.ds.common.exception.RRException;
  4. import com.ds.common.result.Result;
  5. import com.ds.crawler.search.service.MallSearchService;
  6. import com.ds.crawler.search.service.thirdParty.ExportToExcel;
  7. import com.ds.model.CrawlerResultModel;
  8. import com.ds.model.SearchParam;
  9. import lombok.extern.slf4j.Slf4j;
  10. import org.springframework.beans.factory.annotation.Autowired;
  11. import org.springframework.web.bind.annotation.CrossOrigin;
  12. import org.springframework.web.bind.annotation.GetMapping;
  13. import org.springframework.web.bind.annotation.RequestMapping;
  14. import org.springframework.web.bind.annotation.RestController;
  15. import javax.servlet.http.HttpServletResponse;
  16. import java.io.File;
  17. import java.io.FileInputStream;
  18. import java.io.File;
  19. import java.io.FileInputStream;
  20. import java.io.IOException;
  21. import javax.servlet.http.HttpServletResponse;
  22. import org.springframework.http.HttpHeaders;
  23. import org.springframework.http.HttpStatus;
  24. import org.springframework.http.MediaType;
  25. import org.springframework.http.ResponseEntity;
  26. import org.springframework.stereotype.Controller;
  27. import org.springframework.web.bind.annotation.GetMapping;
  28. @Slf4j
  29. @RestController
  30. @RequestMapping("/search/product")
  31. @CrossOrigin
  32. public class ExportConroller {
  33. @Autowired
  34. MallSearchService mallSearchService;
  35. @GetMapping("/export")
  36. public ResponseEntity<byte[]> export(SearchParam param, HttpServletResponse response) throws IOException {
  37. // 1、 根据要求查询数据
  38. CrawlerResultModel result = mallSearchService.search(param);
  39. if (result!=null&&result.getProduct()!=null){
  40. // 2、 将数据导入excel
  41. Boolean b = ExportToExcel.exportToExcel(result.getProduct());
  42. // 3、转为字节流返回给前端
  43. if(b){
  44. File file = new File("E:\\GonZuoShi\\java\\crawler\\crawler-es\\products.xlsx");
  45. // 将Excel文件读取到字节数组中
  46. FileInputStream fileInputStream = new FileInputStream(file);
  47. byte[] bytes = new byte[(int) file.length()];
  48. fileInputStream.read(bytes);
  49. fileInputStream.close();
  50. // 设置响应头
  51. HttpHeaders headers = new HttpHeaders();
  52. headers.setContentType(MediaType.parseMediaType("application/vnd.ms-excel"));
  53. headers.setContentDispositionFormData("attachment", "products.xlsx");
  54. // 返回响应实体
  55. return ResponseEntity.ok()
  56. // .headers(headers)
  57. // .contentLength(bytes.length)
  58. .body(bytes);
  59. }else{
  60. //抛出异常
  61. throw new RRException(BizCodeEnume.EXPORT_TO_EXCEPTION.getMsg(),BizCodeEnume.EXPORT_TO_EXCEPTION.getCode());
  62. }
  63. }else{
  64. //抛出异常
  65. throw new RRException(BizCodeEnume.EXPORT_TO_EXCEPTION.getMsg(),BizCodeEnume.EXPORT_TO_EXCEPTION.getCode());
  66. }
  67. }
  68. }

这样前端就收会收到一个二进制的文件流

前端获取文件流:

使用axios 请求:

创建request:

  1. exportExcel(data){
  2. return request{
  3. url:'....',
  4. port:get,
  5. data:data,
  6. responseType:'arraybuffer',
  7. }
  8. }

调用:

  1. proxy.$api.downloadcode({site:store.state.siteName}).then(res=>{
  2. const link=document.createElement('a');
  3. // let blob = new Blob([res.data],{type: 'applicationnd.ms-excel'}); //如果后台返回的不是blob对象类型,先定义成blob对象格式
  4. try {
  5. let blob = new Blob([res.data], { type: 'application/octet-stream' }) //如果后台返回的直接是blob对象类型,直接获取数据
  6. // let _fileName = res.headers['content-disposition'].split(';')[1].split('=')[1]; //拆解获取文件名,
  7. link.style.display='none';
  8. // 兼容不同浏览器的URL对象
  9. const url = window.URL || window.webkitURL || window.moxURL;
  10. link.href=url.createObjectURL(blob);
  11. link.download =`${store.state.siteName}.xlsx`; //下载的文件名称
  12. link.click();
  13. window.URL.revokeObjectURL(url); // #URL.revokeObjectURL()方法会释放一个通过URL.createObjectURL()创建的对象URL. 当你要已经用过了这个对象URL,然后要让浏览器知道这个URL已经不再需要指向对应的文件的时候,就需要调用这个方法.
  14. }catch(e){
  15. console.log('下载的文件出错',e)
  16. }
  17. })

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/842505
推荐阅读
相关标签
  

闽ICP备14008679号