java根据url获取文件的类型

前言

今天前端突然过来要我出个接口,想要知道图片url的类型,他需要生成图片指定后缀,由于我们的图片是存储在阿里云的oss上,文件url都是类似这种:https://imgistory.xxx.com/cs/f52361f41b55bc780162e32ef128ba2a,个人感觉还是挺有趣的,然后记一下。

介绍

在java的java.net包下有个HttpURLConnection类,大家应该不陌生,用来访问http协议,以下是对这个类的介绍

 

 查看数据结构发现只提供了一个有参构造,需要一个url地址

 在这个类中有两个方法可以查询到文件类型

1、根据文件名,这种方法不适用我们的url,而且不是很准确

2、根据url的字节流查询开头字符,这中直接针对于文件,几乎准确率达到百分百

 所以我们选择第二种方式获取,这个方法需要一个input输入流,所以我们需要将URL转为io流,代码如下:

package net.novelcomic.server.console.action.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import net.novelcomic.server.console.model.vo.bookchapter.Inputs;
import net.novelcomic.server.console.service.common.CommonService;
import net.pailing.kandian.framework.core.vo.BaseRsp;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author cai
 * @className CommonController
 * @description 通用
 * @dateTime 2023/2/22 10:22
 */
@Api(tags = {"通用"})
@RestController
@RequestMapping("/common")
@RequiredArgsConstructor
public class CommonController {

    private final CommonService commonService;

    @ApiOperation("获取文件类型")
    @RequestMapping("/fileType")
    public BaseRsp<String> getFileType(@RequestBody Inputs ro) {
        return new BaseRsp<>(commonService.getFileType(ro.getText()));
    }
}
package net.novelcomic.server.console.service.common;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

@Service
@Slf4j
public class CommonService {
    /**
     * 获取url文件类型
     *
     * @param file
     * @return
     */
    public String getFileType(String file) {
        BufferedInputStream bis = null;
        HttpURLConnection urlconnection = null;
        URL url = null;
        try {
            url = new URL(file);
            urlconnection = (HttpURLConnection) url.openConnection();
            urlconnection.connect();
            bis = new BufferedInputStream(urlconnection.getInputStream());
            return HttpURLConnection.guessContentTypeFromStream(bis);
        } catch (IOException e) {
            log.error("获取url文件类型异常,file:{},excption:{}", file, e.getMessage());
        }
        return null;
    }
}

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值