美文网首页
spring webFlux文件上传/下载

spring webFlux文件上传/下载

作者: 毛于晏 | 来源:发表于2020-04-07 16:33 被阅读0次

springMvc的文件上传后端通过MultipartFile对象接收, 但是webFlux无法使用该对象接收
可通过如下方法:

import lombok.Data;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.http.*;
import org.springframework.http.codec.multipart.FilePart;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
    //文件上传
    @PostMapping("/upload")
    public String upload(FilePart filePart) throws Exception{
        //获取path对象, 第一个参数随意填写
        Path path = Files.createTempFile("test", filePart.filename());
        //目前不知道干啥用的, 有知道的老哥请留言
        filePart.transferTo(path);

        //获得file对象
        File file = new File(path.toString());

        //转换为buff输入流
        FileReader fileReader = new FileReader(file);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        String str = "";
        while ((str = bufferedReader.readLine()) != null) {
            System.out.println(str);
        }
        return "OK";
    }

    //文件下载
    @GetMapping("/download")
    public ResponseEntity<byte[]> downloadByWriteWith() throws Exception {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        //防止中文文件名不显示
        String downloadFileName = URLEncoder.encode("字符串下载文件.txt","UTF-8");
        headers.setContentDispositionFormData("attachment", downloadFileName);

        String str = "123你好啊";
        byte[] bytes1 = str.getBytes();
//        File file = new File("");
//        byte[] bytes = Files.readAllBytes(file.toPath());
        return new ResponseEntity<byte[]>(bytes1, headers, HttpStatus.CREATED);
    }

    @Data
    class Meals{
        private String tcqd;
        private String wxbs;
        private String tcbm;
        private String yhdd;
        private String sjxm;
        private String sjdz;
        private String lxfs;
        private String sjjg;
        private String sjlx;
        private String sbkh;
    }
    //excel导出
    @GetMapping("/excel")
    public Mono<Void> downloadExcel(ServerHttpResponse response) throws Exception {
        //构建数据
        List<Meals> mealsList = new ArrayList<>();
        Meals meals = new Meals();
        meals.setTcqd("0001");
        meals.setTcbm("000254");
        meals.setWxbs("asdfadxoiwnhFSAK");
        meals.setYhdd("FDSDFK00125");
        meals.setSjxm("liumin");
        meals.setSjdz("shengtangdasha");
        meals.setLxfs("12398432498");
        meals.setSjjg("6541");
        meals.setSjlx("ddddddd");
        meals.setSbkh("555555");

        Meals meals1 = new Meals();
        meals1.setTcqd("0002");
        meals1.setTcbm("0002232323");
        meals1.setWxbs("asdfadxoiwnhFSAK");
        meals1.setYhdd("FDSDFK00125");
        meals1.setSjxm("liumin");
        meals1.setSjdz("shengtangdasha");
        meals1.setLxfs("12398432498");
        meals1.setSjjg("6541");
        meals1.setSjlx("啊啊啊啊啊啊啊啊啊啊啊啊啊");
        meals1.setSbkh("666666666666");
        mealsList.add(meals);
        mealsList.add(meals1);

        //Excel表头
        String []title = {"套餐渠道","套餐编码","微信标识","用户订单","收件姓名","收件地址","联系方式","收件价格","收件类型","设备卡号"};
        //sheet名
        String sheetName = "套餐信息";
        String fileName = "套餐信息列表.xls";

        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet(sheetName);
        HSSFRow row = sheet.createRow(0);
        //这里用了两次独立的for循环,我觉得这样思路更清晰,你也可以用嵌套循环
        for (int i=0;i<title.length;i++){
            HSSFCell cell = row.createCell(i);
            cell.setCellValue(title[i]);
            //列宽自适应好像不生效
            sheet.autoSizeColumn(i);
            //解决了列头自适应
            sheet.setColumnWidth(i,title[i].getBytes().length*256);
        }
        for (int i=0;i<mealsList.size();i++){
            row = sheet.createRow(i+1);
            Meals m = mealsList.get(i);
            row.createCell(0).setCellValue(m.getTcqd());
            row.createCell(1).setCellValue(m.getTcbm());
            row.createCell(2).setCellValue(m.getWxbs());
            row.createCell(3).setCellValue(m.getYhdd());
            row.createCell(4).setCellValue(m.getSjxm());
            row.createCell(5).setCellValue(m.getSjdz());
            row.createCell(6).setCellValue(m.getLxfs());
            row.createCell(7).setCellValue(m.getSjjg());
            row.createCell(8).setCellValue(m.getSjlx());
            row.createCell(9).setCellValue(m.getSbkh());
        }
        return Mono.fromCallable(() -> {
            File file = new File(fileName);
            workbook.write(new FileOutputStream(file));
            return file;
        }).flatMap(file -> downloadFile(response, file, fileName));

    }

    private Mono<Void> downloadFile(ServerHttpResponse response, File file, String fileName) {
        ZeroCopyHttpOutputMessage zeroCopyHttpOutputMessage = (ZeroCopyHttpOutputMessage) response;
        try {
            response.getHeaders()
                    .set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=".concat(
                            URLEncoder.encode(fileName, StandardCharsets.UTF_8.displayName())));
            return zeroCopyHttpOutputMessage.writeWith(file, 0, file.length());
        } catch (UnsupportedEncodingException e) {
            throw new UnsupportedOperationException();
        }
    }

相关文章

网友评论

      本文标题:spring webFlux文件上传/下载

      本文链接:https://www.haomeiwen.com/subject/yhunphtx.html