前言
今天前端突然过来要我出个接口,想要知道图片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;
}
}