其他分享
首页 > 其他分享> > springboot 模拟上次文件: MultipartFile + json餐食

springboot 模拟上次文件: MultipartFile + json餐食

作者:互联网

首先来看,接口及参数

 

 

postman模拟上传

 

 

 

需求:将生成好的,远程excel附件,以及一些常规数据通过接口,传递过去。

代码部分:

1.将远程excel附件,转化为MultipartFile

public class FileToMultipartFileUtils {

    /**
     * 远程file文件转MultipartFile
     * @param fileContentType
     * @param filePath
     * @return
     */
    public static MultipartFile getMultipartFile(String fileContentType, String filePath) {
        MultipartFile multipartFile = null;
        try {
            //文件转MultipartFile
            log.info("文件转MultipartFile, fileContentType:{}, filePath:{}",fileContentType, filePath);

            URL url = new URL(filePath);
            DataSource dataSource = new URLDataSource(url);
            DataHandler dataHandler = new DataHandler(dataSource);
            DiskFileItem fileItem = (DiskFileItem) new DiskFileItemFactory().createItem("file",
                    MediaType.ALL_VALUE, true, dataHandler.getName());
            IOUtils.copy(dataHandler.getInputStream(), fileItem.getOutputStream());
            multipartFile = new CommonsMultipartFile(fileItem);
        }catch (Exception e){
            e.printStackTrace();
            log.error("文件转MultipartFile失败-err:{}",e.getMessage());
        }
        return multipartFile;
    }



}

  

2.主程序部分

@Override
    public void postMailByMealOrder() {
        Calendar rightNow = Calendar.getInstance();
        int hour = rightNow.get(Calendar.HOUR_OF_DAY);
        String startFltDate = null;
        String endFltDate = null;
        String currentDate = ComDateUtils.dateToStr(ComDateUtils.plusHours(new Date(), 24), ComDateUtils.YYYY_MM_DD);
        if(hour <= 6){
            //06:00:处理次日06-14(含)
            startFltDate = currentDate + " 06:00:00";
            endFltDate =  currentDate + " 14:00:00";
        }else if(hour <= 14){
            //14:00:处理次日14-22(含)
            startFltDate = currentDate + " 14:00:00";
            endFltDate =  currentDate + " 22:00:00";
        }else if(hour <= 22){
            //22:00:处理次日22-第三日06(含)
            startFltDate =  currentDate + " 22:00:00";
            String lastDate = ComDateUtils.dateToStr(ComDateUtils.plusDays(new Date(), 2), ComDateUtils.YYYY_MM_DD);
            endFltDate =  lastDate + " 06:00:00";
        }else{
            return;
        }
        doOrderMealSummary(startFltDate, endFltDate);

    }
    private void doOrderMealSummary(String startFltDate, String endFltDate){

        if(StringUtils.isEmpty(startFltDate) || StringUtils.isEmpty(endFltDate))
            return;
        //参数
        MealSummaryQueryDTO queryDTO = new MealSummaryQueryDTO();
        queryDTO.setFltDateStart(startFltDate);
        queryDTO.setFltDateEnd(endFltDate);
        //数据查询
        List<ExportMealSummaryBO> summaryBOS = orderMealSummaryService.adminExportTask(queryDTO);
        if(summaryBOS==null || summaryBOS.size() < 1){
            log.error("餐食订单汇总表-数据统计 is empty.");
            return;
        }
        List<ExportMealOrderSummaryBO> orderSummaryBOS =  orderMealInfoService.adminExportBySummaryTask(queryDTO);
        //创建excel,并生成远程excel
        ExcelMealSummaryUtil util = new ExcelMealSummaryUtil<>();
        Workbook wb = new SXSSFWorkbook(500);
        util.exportDataToCell(wb, ExportMealSummaryBO.class, summaryBOS,0,"餐食订单汇总表");
        util.exportDataToCell(wb, ExportMealOrderSummaryBO.class,  orderSummaryBOS,1,"餐食订单明细表");
        AjaxResult result =  util.exportExcelToFile(wb, "meal");
        String filePath = riakPubUrl + "/" + (String) result.get("msg");
        //sendMailService(filePath, null);
        //发送邮件
        //String filePath = "http://192.168.203.99:8098/buckets/joy-air/keys/meal_62ebfb4f-d69d-47cd-ac15-c6904aba977b.xlsx";
        sendMailService(filePath, null);
    }

  

上传附件,部分

private boolean sendMailService(String filePath, List<ExportMealSummaryBO> summaryBOS){

        MultipartFile multipartFile = null;
        try{
            multipartFile =  FileToMultipartFileUtils.getMultipartFile("application/pdf",   filePath);
        }catch (Exception e){
            e.printStackTrace();
            log.error("文件转MultipartFile:err:{}", e.getMessage());
            return false;
        }

        List<MailMealOrder> mailMealOrders = new ArrayList<>();
        MailMealOrder mailMealOrder = new MailMealOrder();
        mailMealOrder.setFlightNo("JR1111");
        mailMealOrder.setFrom("天津");
        mailMealOrder.setTo("淮安");
        mailMealOrder.setFlightDate("2022-01-22");
        mailMealOrder.setDepartureTime("08:00:00");

        List<MealMealInfo> mealMealInfos = new ArrayList<>();
        MealMealInfo mealMealInfo = new MealMealInfo();
        mealMealInfo.setName("香菇滑鸡");
        mealMealInfo.setCount(10);
        mealMealInfos.add(mealMealInfo);
        mailMealOrder.setMealList(mealMealInfos);
        mailMealOrders.add(mailMealOrder);

        Map<String, Object> itemParams = new HashMap<>();
        itemParams.put("companyName", "");
        String[] TO_MAILS = {"muyang@variflight.com"};
        itemParams.put("to",  TO_MAILS);
        itemParams.put("cc", TO_MAILS);
        itemParams.put("type", 1);
        itemParams.put("orderList", mailMealOrders);
        String param= JSON.toJSONString(itemParams);

        Map<String, String> resultMap = new HashMap<String, String>();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = "";
        try {
            HttpPost httpPost = new HttpPost(mailService + "/variflight/sendMail/summarize");
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            //	文件传输http请求头(multipart/form-data)
            builder.addBinaryBody("file", multipartFile.getInputStream(), ContentType.MULTIPART_FORM_DATA,
                   multipartFile.getOriginalFilename());// 文件流
            //	字节传输http请求头(application/json)
            builder.addTextBody("summarize", param, ContentType.APPLICATION_JSON);//字节流

            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);
            // 执行提交
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                // 将响应内容转换为字符串
                result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
            }
            JSONObject jsonObj = JSONObject.parseObject(result);
            if ( jsonObj.getString("code").equals("0") ){
                return true;
            }else{
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("调用发送邮件接口出错: message:{}", e.getMessage());
        }finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return false;
    }

  

 

标签:null,String,filePath,mailMealOrder,餐食,json,new,MultipartFile,springboot
来源: https://www.cnblogs.com/achengmu/p/15827467.html