package com.epmet.controller; import com.epmet.commons.tools.exception.EpmetErrorCode; import com.epmet.commons.tools.exception.EpmetException; import com.epmet.commons.tools.utils.DateUtils; import com.epmet.commons.tools.utils.FileUtils; import com.epmet.commons.tools.utils.Result; import com.epmet.service.LingShanSpecialCrowdService; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Date; /** * @description: 灵山社会维稳(特殊人群) * @param null: * @return * @author: WangXianZhang * @date: 2023/4/18 9:08 AM */ @Slf4j @RestController @RequestMapping("lingShan/specialCrowd") public class LingShanSpecialCrowdController { @Autowired private LingShanSpecialCrowdService lingShanSpecialCrowdService; /** * @description: 特殊人群导入 * @param file: * @param crowdCategory: 人群类别 * anzhibangjiao * buliangqingshaonian * shequjiaozheng * xidurenyuan * xiejiaorenyuan * zhaoshizhaohuojingshenbing * @return * @author: WangXianZhang * @date: 2023/4/18 9:12 AM */ @PostMapping("import") public Result importSpecialCowd(MultipartFile file, @RequestParam("crowdCategory") String crowdCategory) { String originalFilename = file.getOriginalFilename(); String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")); // 1.存文件 Path fileSavePath = saveSpecialCrowdTempFile(file, suffix); // 2.执行业务导入 try { lingShanSpecialCrowdService.importSpecialCrowd(crowdCategory, fileSavePath.toString(), originalFilename); } catch (Exception e) { // 3.出错的话,删除文件 FileUtils.deleteFileIfExists(fileSavePath); throw e; } return new Result(); } /** * @description: 保存特殊人群临时文件 * @param file: * @return * @author: WangXianZhang * @date: 2023/4/18 9:46 AM */ public Path saveSpecialCrowdTempFile(@RequestParam("file") MultipartFile file, String suffix) { Path fileSavePath; FileOutputStream os = null; try { Path fileSaveDir = FileUtils.getAndCreateDirUnderEpmetFilesDir("special_crowd_import"); String fileName = DateUtils.format(new Date(), "yyyyMMdd_HHmmss_" + System.nanoTime()) + suffix; fileSavePath = fileSaveDir.resolve(fileName); IOUtils.copy(file.getInputStream(), (os = new FileOutputStream(fileSavePath.toString()))); return fileSavePath; } catch (IOException e) { log.error("【灵山街道】导入社会维稳数据,缓存文件失败。"); throw new EpmetException(EpmetErrorCode.EPMET_COMMON_OPERATION_FAIL.getCode(), null, null); } finally { org.apache.poi.util.IOUtils.closeQuietly(os); } } }