文件上傳服務(wù)

一、 配置文件

aliyun:
  oss:
    enable: true
    accessKey: 
    secretKey: 
    endpoint: 
    publicBucket: 
    publicDownUrl:

二辜昵、 文件上傳接口

public interface FileUploadService {

    /**
     * 上傳文件到外網(wǎng)可直接訪問(wèn)的oss中
     *
     * @param file
     * @param moduleName
     * @return
     * @throws BaseException
     */
    String uploadPublic(MultipartFile file, String moduleName) throws BaseException;

    /**
     * 上傳文件到外網(wǎng)可以直接訪問(wèn)的oss中
     * @param file
     * @param moduleName
     * @return
     * @throws BaseException
     */
    String uploadPublic(File file, String moduleName) throws BaseException;

    /**
     * 下載文件
     *
     * @param path
     * @return 返回inputstream,使用完畢后需要關(guān)閉
     * @throws BaseException
     */
    public InputStream downloadPublic(String path) throws BaseException;

    /**
     * 根據(jù)路徑獲取oss完整地址
     *
     * @param path
     * @return
     * @throws BaseException
     */
    String getWholeOSSPath(String path) throws BaseException;

    /**
     * 上傳文件到外網(wǎng)可直接訪問(wèn)的oss中
     *
     * @param file
     * @param moduleName
     * @return
     * @throws BaseException
     */
    String uploadCompress(MultipartFile file, String moduleName) throws BaseException;


    /**
     * 上傳壓縮文件并校驗(yàn)
     *
     * @param file
     * @param moduleName
     * @param name
     * @param idno
     * @return
     * @throws BaseException
     */
    String uploadCheckCompress(MultipartFile file, String moduleName, String name, String idno, String orderId, String type) throws Exception;
}

三咽斧、 文件上傳實(shí)現(xiàn)類

/**
 * 文件上傳服務(wù)
 *
 * @author HT
 * @version 1.0
 * @since 2022-03-10 11:04
 */
@Service
public class FiileUploadServiceImpl implements FileUploadService {

    private static Logger LOGGER = LoggerFactory.getLogger(FiileUploadServiceImpl.class);

    @Autowired(required = false)
    private OSS ossClient;

    @Value("${aliyun.oss.publicBucket:}")
    private String publicBucket;

    @Value("${spring.application.name:}")
    private String projectName;

    @Value("${aliyun.oss.publicDownUrl:}")
    private String publicDownUrl;

    @Override
    public String uploadPublic(MultipartFile file, String moduleName) throws BaseException {
        if (StringUtils.isBlank(moduleName)) {
            throw new BaseException("moduleName參數(shù)不能為空");
        }
        String name = file.getOriginalFilename();
        String objetName = this.getPath(moduleName, name);
        String ext = StringUtils.substring(name, name.lastIndexOf(".") + 1);
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType(ContentTypeUtils.getValue(ext));
        InputStream input = null;
        try {
            input = file.getInputStream();
            PutObjectResult putObjectResult = this.ossClient.putObject(publicBucket, objetName, input, objectMetadata);
        } catch (Exception e) {
            throw new BaseException("文件上傳失敗" + e.getMessage());
        } finally {
            try {
                if (input != null) {
                    input.close();
                }
            } catch (IOException ex) {
                throw new BaseException("上傳文件失敗堪置,關(guān)閉輸入流異常:" + ex.getMessage());
            }
        }
        return objetName;
    }


    @Override
    public String uploadPublic(File file, String moduleName) throws BaseException {
        if (StringUtils.isBlank(moduleName)) {
            throw new BaseException("moduleName參數(shù)不能為空");
        }

        String name = file.getName();
        String objetName = this.getPath(moduleName, name);
        String ext = StringUtils.substring(name, name.lastIndexOf(".") + 1);
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType(ContentTypeUtils.getValue(ext));
        InputStream input = null;
        try {
            input = new FileInputStream(file);
            PutObjectResult putObjectResult = this.ossClient.putObject(publicBucket, objetName, input, objectMetadata);
        } catch (Exception e) {
            throw new BaseException("文件上傳失敗" + e.getMessage());
        } finally {
            try {
                if (input != null) {
                    input.close();
                }
            } catch (IOException ex) {
                throw new BaseException("上傳文件失敗,關(guān)閉輸入流異常:" + ex.getMessage());
            }
        }
        return objetName;
    }

    @Override
    public InputStream downloadPublic(String path) throws BaseException {
        if (StringUtils.isBlank(path)) {
            throw new BaseException("path不能為空");
        }
        return this.ossClient.getObject(publicBucket, path).getObjectContent();
    }

    private String getPath(String moduleName, String fileName) {
        String ext = StringUtils.substring(fileName, fileName.lastIndexOf("."));
        String uuid = IDUtils.randomUUID();
        String nowStr = DateUtils.formate(LocalDate.now(), "yyyyMMdd");
        String objectName = this.projectName + "/" + moduleName + "/" + nowStr + "/" + uuid + ext;

        return objectName;
    }

    /**
     * 后去oss的完整路徑
     *
     * @param path
     * @return
     */
    @Override
    public String getWholeOSSPath(String path) throws BaseException {
        if (StringUtils.endsWith(this.publicDownUrl, "/")
                && StringUtils.startsWith(path, "/")) {
            return this.publicDownUrl + StringUtils.substring(path, 1);
        } else if (StringUtils.endsWith(this.publicDownUrl, "/")
                || StringUtils.startsWith(path, "/")) {
            return this.publicDownUrl + path;
        } else {
            return this.publicDownUrl + "/" + path;
        }
    }

    @Override
    public String uploadCompress(MultipartFile file, String moduleName) throws BaseException {
        if (StringUtils.isBlank(moduleName)) {
            throw new BaseException("moduleName參數(shù)不能為空");
        }
        String name = file.getOriginalFilename();
        String objetName = this.getPath(moduleName, name);
        String ext = StringUtils.substring(name, name.lastIndexOf(".") + 1);
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType(ContentTypeUtils.getValue(ext));
        InputStream input = null;
        InputStream inputStream = null;
        try {
            input = file.getInputStream();
            inputStream = handlerImg(input, name);
            PutObjectResult putObjectResult = this.ossClient.putObject(publicBucket, objetName, inputStream, objectMetadata);
        } catch (Exception e) {
            throw new BaseException("文件上傳失敗" + e.getMessage());
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException ex) {
                throw new BaseException("上傳文件失敗张惹,關(guān)閉輸入流異常:" + ex.getMessage());
            }
        }
        return objetName;
    }

    @Override
    public String uploadCheckCompress(MultipartFile file, String moduleName, String name, String idno, String orderId, String type) throws Exception {
        if (StringUtils.isBlank(moduleName)) {
            throw new Exception("moduleName參數(shù)不能為空");
        }
        String data = OcrUtils.ocrCheck(file.getInputStream(),orderId,type);
        if("300".equals(data)){
            return data;
        }
        Map map = JSON.parseObject(data, Map.class);
        JSONObject dataInfo = (JSONObject) map.get("data");
        JSONObject face = (JSONObject) dataInfo.get("face");
        JSONObject cardInfo = (JSONObject) face.get("data");
        if (cardInfo.get("idNumber").equals(idno)){
            if (cardInfo.get("name").equals(name)){
                String fileName = file.getOriginalFilename();
                String objetName = this.getPath(moduleName, fileName);
                String ext = StringUtils.substring(fileName, fileName.lastIndexOf(".") + 1);
                ObjectMetadata objectMetadata = new ObjectMetadata();
                objectMetadata.setContentType(ContentTypeUtils.getValue(ext));
                InputStream input = null;
                InputStream inputStream = null;
                try {
                    input = file.getInputStream();
                    inputStream = handlerImg(input, fileName);
                    PutObjectResult putObjectResult = this.ossClient.putObject(publicBucket, objetName, inputStream, objectMetadata);
                } catch (Exception e) {
                    throw new BaseException("文件上傳失敗" + e.getMessage());
                } finally {
                    try {
                        if (inputStream != null) {
                            inputStream.close();
                        }
                    } catch (IOException ex) {
                        throw new BaseException("上傳文件失敗舀锨,關(guān)閉輸入流異常:" + ex.getMessage());
                    }
                }
                return objetName;
            }else{
                return "300";
            }
        }else {
            return "300";
        }
    }

    private static InputStream handlerImg(InputStream input, String fileName) {

        String extName = org.apache.commons.lang.StringUtils.substring(fileName, fileName.lastIndexOf(".") + 1);
        InputStream newInput = null;
        try {
            BufferedImage thumbnail = Thumbnails.of(input).scale(0.8f).imageType(BufferedImage.TYPE_INT_ARGB).outputQuality(0.4).asBufferedImage();
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            BufferedImage bufferedImage = getBufferedImage(thumbnail);
            ImageIO.write(bufferedImage, extName, os);
            newInput = new ByteArrayInputStream(os.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (input != null) {
                    input.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return newInput;
    }

    public static BufferedImage getBufferedImage(BufferedImage thumbnail) throws MalformedURLException {
//        URL url = new URL(imgUrl);
//        ImageIcon icon = new ImageIcon(url);
//        Image image = icon.getImage();

        // 如果是從本地加載,就用這種方式宛逗,沒(méi)親自測(cè)試過(guò)
        Image image = thumbnail;

        // This code ensures that all the pixels in the image are loaded
        BufferedImage bimage = null;
        GraphicsEnvironment ge = GraphicsEnvironment
                .getLocalGraphicsEnvironment();
        try {
            int transparency = Transparency.OPAQUE;
            GraphicsDevice gs = ge.getDefaultScreenDevice();
            GraphicsConfiguration gc = gs.getDefaultConfiguration();
            bimage = gc.createCompatibleImage(image.getWidth(null),
                    image.getHeight(null), transparency);
        } catch (HeadlessException e) {
            // The system does not have a screen
        }
        if (bimage == null) {
            // Create a buffered image using the default color model
            int type = BufferedImage.TYPE_INT_RGB;
            bimage = new BufferedImage(image.getWidth(null),
                    image.getHeight(null), type);
        }
        // Copy image to buffered image
        Graphics g = bimage.createGraphics();
        // Paint the image onto the buffered image
        g.drawImage(image, 0, 0, null);
        g.dispose();
        return bimage;
    }
}

四坎匿、 文件上傳實(shí)現(xiàn)類

/**
 * 基礎(chǔ)controller,其他web類需繼承此controller
 *
 * @author HT
 * @version 1.0
 * @date 2022-03-10 14:44
 */
@RestController
@Api(value = "通用接口--文件上傳", tags = "通用接口--文件上傳", position = 0)
public class FileUploadController {

    @Autowired
    private FileUploadService service;


    @ApiOperation("文件上傳")
    @RequestMapping(value = "/file/upload/public",method = RequestMethod.POST)
    @ResponseBody
    public Result<String> uploadPublic(@RequestParam("file") MultipartFile file, @RequestParam("module") String moduleName) {
        Result<String> result = Result.of();
        result.success("上傳成功").setData(this.service.uploadPublic(file, moduleName));
        return result;
    }

    @PostMapping("/file/uploadFile")
    @ApiOperation(value = "文件上傳(同時(shí)保存數(shù)據(jù)庫(kù))")
    public Result<String> uploadFile(HttpServletRequest request, @RequestBody List<MultipartFile> file,@RequestParam("module") String moduleName){
        Result<String> result = Result.of();
        if(file == null || file.size() <= 0){
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultiValueMap<String, MultipartFile> fileMap = multipartRequest.getMultiFileMap();
            file = new ArrayList<MultipartFile>(); 
            for (String ss : fileMap.keySet()) {
                System.out.println(ss);
                file.add(fileMap.get(ss).get(0));
            }
        }
        List<FileInfo> fileInfos = this.service.uploadFile(file,moduleName);
        result.success().setData(fileInfos);
        return result;
    }

    @ApiOperation("文件壓縮上傳")
    @RequestMapping(value = "/file/upload/compress",method = RequestMethod.POST)
    @ResponseBody
    public Result<String> uploadCompress(@RequestParam("file") MultipartFile file, @RequestParam("module") String moduleName) {
        Result<String> result = Result.of();
        result.success("上傳成功").setData(this.service.uploadCompress(file, moduleName));
        return result;
    }

    @ApiOperation("文件壓縮校驗(yàn)上傳")
    @RequestMapping(value = "/file/uploadCheck/compress",method = RequestMethod.POST)
    @ResponseBody
    public Result<String> uploadCheckCompress(@RequestParam("file") MultipartFile file, @RequestParam("moduleName") String moduleName, @RequestParam("name") String name, @RequestParam("idno") String idno, @RequestParam("orderId") String orderId, @RequestParam("type") String type) throws Exception {
        Result<String> result = Result.of();
        result.success("200").setData(this.service.uploadCheckCompress(file, moduleName, name, idno, orderId, type));
        return result;
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市雷激,隨后出現(xiàn)的幾起案子碑诉,更是在濱河造成了極大的恐慌,老刑警劉巖侥锦,帶你破解...
    沈念sama閱讀 216,372評(píng)論 6 498
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異德挣,居然都是意外死亡恭垦,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,368評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門(mén)格嗅,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)番挺,“玉大人,你說(shuō)我怎么就攤上這事屯掖⌒兀” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 162,415評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵贴铜,是天一觀的道長(zhǎng)粪摘。 經(jīng)常有香客問(wèn)我,道長(zhǎng)绍坝,這世上最難降的妖魔是什么徘意? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,157評(píng)論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮轩褐,結(jié)果婚禮上椎咧,老公的妹妹穿的比我還像新娘。我一直安慰自己把介,他們只是感情好勤讽,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,171評(píng)論 6 388
  • 文/花漫 我一把揭開(kāi)白布蟋座。 她就那樣靜靜地躺著,像睡著了一般脚牍。 火紅的嫁衣襯著肌膚如雪向臀。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,125評(píng)論 1 297
  • 那天莫矗,我揣著相機(jī)與錄音飒硅,去河邊找鬼。 笑死作谚,一個(gè)胖子當(dāng)著我的面吹牛三娩,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播妹懒,決...
    沈念sama閱讀 40,028評(píng)論 3 417
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼雀监,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了眨唬?” 一聲冷哼從身側(cè)響起会前,我...
    開(kāi)封第一講書(shū)人閱讀 38,887評(píng)論 0 274
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎匾竿,沒(méi)想到半個(gè)月后瓦宜,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,310評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡岭妖,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,533評(píng)論 2 332
  • 正文 我和宋清朗相戀三年临庇,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片昵慌。...
    茶點(diǎn)故事閱讀 39,690評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡假夺,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出斋攀,到底是詐尸還是另有隱情已卷,我是刑警寧澤,帶...
    沈念sama閱讀 35,411評(píng)論 5 343
  • 正文 年R本政府宣布淳蔼,位于F島的核電站侧蘸,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏鹉梨。R本人自食惡果不足惜闺魏,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,004評(píng)論 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望俯画。 院中可真熱鬧析桥,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,659評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至娩怎,卻和暖如春搔课,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背截亦。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,812評(píng)論 1 268
  • 我被黑心中介騙來(lái)泰國(guó)打工爬泥, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人崩瓤。 一個(gè)月前我還...
    沈念sama閱讀 47,693評(píng)論 2 368
  • 正文 我出身青樓袍啡,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親却桶。 傳聞我的和親對(duì)象是個(gè)殘疾皇子境输,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,577評(píng)論 2 353

推薦閱讀更多精彩內(nèi)容