最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Springboot?返回文件給前端的示例代碼

 更新時(shí)間:2023年07月05日 11:24:29   作者:屎碼程序員  
這篇文章主要介紹了Springboot?返回文件給前端的示例代碼,本文結(jié)合示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

首先導(dǎo)入數(shù)據(jù)到excel中

package com.ds.crawler.search.service.thirdParty;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import com.ds.model.CrawlerModel;
import com.ds.model.CrawlerResultModel;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public  class ExportToExcel {
    public static Boolean exportToExcel(List<CrawlerModel> products){
        // 創(chuàng)建工作簿對(duì)象
        XSSFWorkbook workbook = new XSSFWorkbook();
        // 創(chuàng)建工作表對(duì)象
        Sheet sheet = workbook.createSheet("products");
        // 創(chuàng)建表頭行
        Row header = sheet.createRow(0);
        header.createCell(0).setCellValue("ID");
        header.createCell(1).setCellValue("site");
        header.createCell(2).setCellValue("name");
        header.createCell(3).setCellValue("price");
        header.createCell(4).setCellValue("unit");
        header.createCell(5).setCellValue("time");
        header.createCell(6).setCellValue("source");
        header.createCell(7).setCellValue("type");
        header.createCell(8).setCellValue("size");
        header.createCell(9).setCellValue("color");
        header.createCell(10).setCellValue("img");
        header.createCell(11).setCellValue("material");
        header.createCell(12).setCellValue("rank");
        // 填充數(shù)據(jù)
        int rowNum = 1;
        for (CrawlerModel product : products) {
            Row row = sheet.createRow(rowNum);
            row.createCell(0).setCellValue(rowNum);
            row.createCell(1).setCellValue(product.getSite()==null?"":product.getSite());
            row.createCell(2).setCellValue(product.getName()==null?"":product.getName());
            row.createCell(3).setCellValue(((product.getPrice()==null?"":product.getPrice().toString())));
            row.createCell(4).setCellValue(product.getUnit()==null?"":product.getUnit());
            row.createCell(5).setCellValue(product.getTime()==null?"":product.getTime());
            row.createCell(6).setCellValue(product.getSource()==null?"":product.getSource());
            row.createCell(7).setCellValue(product.getType()==null?"":product.getType());
            row.createCell(8).setCellValue(product.getSize()==null?"":product.getSize().toString());
            row.createCell(9).setCellValue(product.getColor()==null?"":product.getColor().toString());
            row.createCell(10).setCellValue(product.getImg()==null?"":product.getImg().toString());
            row.createCell(11).setCellValue(product.getMaterial()==null?"":product.getMaterial());
            row.createCell(12).setCellValue(product.getRank()==null?"":product.getRank().toString());
            rowNum++;
        }
        // 將數(shù)據(jù)寫(xiě)入Excel文件
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream("products.xlsx");
            workbook.write(outputStream);
            workbook.close();
            outputStream.close();
            return true;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

之后就會(huì)看到到處的excel文件了:

創(chuàng)建接口返回文件到前端: 

package com.ds.crawler.search.controller;
import com.ds.common.exception.BizCodeEnume;
import com.ds.common.exception.RRException;
import com.ds.common.result.Result;
import com.ds.crawler.search.service.MallSearchService;
import com.ds.crawler.search.service.thirdParty.ExportToExcel;
import com.ds.model.CrawlerResultModel;
import com.ds.model.SearchParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Slf4j
@RestController
@RequestMapping("/search/product")
@CrossOrigin
public class ExportConroller {
    @Autowired
    MallSearchService mallSearchService;
    @GetMapping("/export")
    public ResponseEntity<byte[]> export(SearchParam param, HttpServletResponse response) throws IOException {
//       1、 根據(jù)要求查詢數(shù)據(jù)
        CrawlerResultModel result = mallSearchService.search(param);
        if (result!=null&&result.getProduct()!=null){
//            2、 將數(shù)據(jù)導(dǎo)入excel
           Boolean b = ExportToExcel.exportToExcel(result.getProduct());
//           3、轉(zhuǎn)為字節(jié)流返回給前端
           if(b){
               File file = new File("E:\\GonZuoShi\\java\\crawler\\crawler-es\\products.xlsx");
               // 將Excel文件讀取到字節(jié)數(shù)組中
               FileInputStream fileInputStream = new FileInputStream(file);
               byte[] bytes = new byte[(int) file.length()];
               fileInputStream.read(bytes);
               fileInputStream.close();
               // 設(shè)置響應(yīng)頭
               HttpHeaders headers = new HttpHeaders();
               headers.setContentType(MediaType.parseMediaType("application/vnd.ms-excel"));
               headers.setContentDispositionFormData("attachment", "products.xlsx");
               // 返回響應(yīng)實(shí)體
               return ResponseEntity.ok()
//                       .headers(headers)
//                       .contentLength(bytes.length)
                       .body(bytes);
           }else{
               //拋出異常
               throw new RRException(BizCodeEnume.EXPORT_TO_EXCEPTION.getMsg(),BizCodeEnume.EXPORT_TO_EXCEPTION.getCode());
           }
        }else{
            //拋出異常
            throw new RRException(BizCodeEnume.EXPORT_TO_EXCEPTION.getMsg(),BizCodeEnume.EXPORT_TO_EXCEPTION.getCode());
        }
    }
}

這樣前端就收會(huì)收到一個(gè)二進(jìn)制的文件流

前端獲取文件流:

使用axios 請(qǐng)求:

創(chuàng)建request:

exportExcel(data){
    return request{
        url:'....',
        port:get,
        data:data,
       responseType:'arraybuffer',
    }
}

調(diào)用:

proxy.$api.downloadcode({site:store.state.siteName}).then(res=>{
          const link=document.createElement('a');
           // let blob = new Blob([res.data],{type: 'applicationnd.ms-excel'});    //如果后臺(tái)返回的不是blob對(duì)象類型,先定義成blob對(duì)象格式
          try {
            let blob =   new Blob([res.data], { type: 'application/octet-stream' })    //如果后臺(tái)返回的直接是blob對(duì)象類型,直接獲取數(shù)據(jù)
	          // let _fileName = res.headers['content-disposition'].split(';')[1].split('=')[1]; //拆解獲取文件名,
	          link.style.display='none';
	          // 兼容不同瀏覽器的URL對(duì)象
	          const url = window.URL || window.webkitURL || window.moxURL;
	          link.href=url.createObjectURL(blob);
	          link.download =`${store.state.siteName}.xlsx`;   //下載的文件名稱
	          link.click();
	          window.URL.revokeObjectURL(url);  //  #URL.revokeObjectURL()方法會(huì)釋放一個(gè)通過(guò)URL.createObjectURL()創(chuàng)建的對(duì)象URL. 當(dāng)你要已經(jīng)用過(guò)了這個(gè)對(duì)象URL,然后要讓瀏覽器知道這個(gè)URL已經(jīng)不再需要指向?qū)?yīng)的文件的時(shí)候,就需要調(diào)用這個(gè)方法.
           }catch(e){
            console.log('下載的文件出錯(cuò)',e)
           }
        })

到此這篇關(guān)于Springboot 返回文件給前端的文章就介紹到這了,更多相關(guān)Springboot 返回給前端內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • java 非對(duì)稱加密算法RSA實(shí)現(xiàn)詳解

    java 非對(duì)稱加密算法RSA實(shí)現(xiàn)詳解

    這篇文章主要介紹了java 非對(duì)稱加密算法RSA實(shí)現(xiàn)詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-07-07
  • java內(nèi)存分布實(shí)現(xiàn)代碼

    java內(nèi)存分布實(shí)現(xiàn)代碼

    這篇文章主要介紹了淺談Java內(nèi)存區(qū)域劃分和內(nèi)存分配策略,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2021-07-07
  • 多層嵌套的json的值如何解析/替換

    多層嵌套的json的值如何解析/替換

    這篇文章主要介紹了多層嵌套的json的值如何解析/替換的方法示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-10-10
  • MyBatisPlus查詢投影與查詢條件詳細(xì)講解

    MyBatisPlus查詢投影與查詢條件詳細(xì)講解

    這篇文章主要介紹了MyBatisPlus DQL編程控制中的查詢投影、查詢條件,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2022-08-08
  • 在Spring使用iBatis及配置講解

    在Spring使用iBatis及配置講解

    今天小編就為大家分享一篇關(guān)于在Spring使用iBatis及配置講解,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧
    2019-01-01
  • springboot項(xiàng)目啟動(dòng)優(yōu)化的超強(qiáng)方法詳解

    springboot項(xiàng)目啟動(dòng)優(yōu)化的超強(qiáng)方法詳解

    本篇文章主要為大家詳細(xì)介紹了SpringBoot中項(xiàng)目啟動(dòng)速度優(yōu)化的方法相關(guān)方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考,一起跟隨小編過(guò)來(lái)看看吧
    2025-10-10
  • java中的4種循環(huán)方法示例詳情

    java中的4種循環(huán)方法示例詳情

    大家好,本篇文章主要講的是java中的4種循環(huán)方法示例詳情,感興趣的同學(xué)趕快來(lái)看一看吧,對(duì)你有幫助的話記得收藏一下,方便下次瀏覽
    2021-12-12
  • 詳解Spring Cloud Eureka多網(wǎng)卡配置總結(jié)

    詳解Spring Cloud Eureka多網(wǎng)卡配置總結(jié)

    本篇文章主要介紹了詳解Spring Cloud Eureka多網(wǎng)卡配置總結(jié),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2018-04-04
  • Java鍵值操作MapUtils的使用小結(jié)

    Java鍵值操作MapUtils的使用小結(jié)

    在Java開(kāi)發(fā)中,鍵值操作是日常工作中不可或缺的一部分,本文主要介紹MapUtils 以org.apache.commons.collections4.MapUtils 為例的工具類實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2026-04-04
  • 聊聊Java中接口重試機(jī)制的幾種解決方案

    聊聊Java中接口重試機(jī)制的幾種解決方案

    接口請(qǐng)求重試機(jī)制是保證系統(tǒng)穩(wěn)定性和容錯(cuò)能力的重要手段之一,當(dāng)接口請(qǐng)求發(fā)生失敗或暫時(shí)性錯(cuò)誤時(shí),通過(guò)重試機(jī)制可以提高請(qǐng)求的成功率,本文將詳細(xì)介紹接口請(qǐng)求重試機(jī)制的幾種常見(jiàn)方法,感興趣的可以了解一下
    2025-07-07

最新評(píng)論

连州市| 天等县| 鲁甸县| 云梦县| 黄冈市| 永泰县| 米林县| 长汀县| 炉霍县| 科技| 大理市| 河间市| 舒城县| 沁阳市| 肃宁县| 泰宁县| 沛县| 陆川县| 昔阳县| 泗水县| 炉霍县| 仲巴县| 平昌县| 资兴市| 旬阳县| 浏阳市| 陕西省| 泰宁县| 宝坻区| 蓬溪县| 华坪县| 汕头市| 乌拉特后旗| 三原县| 分宜县| 涿鹿县| 虞城县| 泰宁县| 宜川县| 永春县| 百色市|