Java如何获取Content-Type的文件类型Mime Type

在Http请求中,有时需要知道Content-Type类型,尤其是上传文件时,更为重要,虽然有些办法可以解决,但都不太准确或者繁琐,索性我发现一个开源的类库能够解决相对完美的解决这个问题,它就是jMimeMagic。

jMimeMagic是一个用来检测文件或者数据流的 MIME 类型的 Java 类库。 最新版本是V 0.1.2。需要jar包:commons-logging-1.0.x.jar,log4j-1.2.x.jar

下载地址:点击打开链接

它的用法很简单,如下:

File file = new File("e:\\test\\123.gif")
MagicMatch match = Magic.getMagicMatch(file, false, true);
String contentType = match.getMimeType();
System.out.println(contentType);

不过,该方法在效率上低一些,算是它的缺点了。

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
以下是Java中使用HttpPost上传图片的封装方法: ```java import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.ByteArrayBody; import org.apache.http.entity.mime.content.ContentBody; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import java.io.IOException; public class HttpUtil { public static String uploadImage(String url, byte[] imageBytes) throws IOException { // 创建HttpClient对象 HttpClient httpClient = HttpClientBuilder.create().build(); // 创建HttpPost对象 HttpPost httpPost = new HttpPost(url); // 创建图片ContentBody对象 ContentBody imageBody = new ByteArrayBody(imageBytes, ContentType.create("image/jpeg"), "image.jpg"); // 创建MultipartEntityBuilder对象,用于封装请求参数 MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addPart("image", imageBody); // 添加图片ContentBody对象 // 将参数封装到HttpEntity中 HttpEntity httpEntity = builder.build(); // 设置请求参数 httpPost.setEntity(httpEntity); // 发送请求并获取响应 HttpResponse response = httpClient.execute(httpPost); // 获取响应实体 HttpEntity entity = response.getEntity(); // 将响应实体转换为字符串 String result = EntityUtils.toString(entity, "UTF-8"); return result; } } ``` 使用方法如下: ```java byte[] imageBytes = ...; // 待上传的图片字节数组 String url = ...; // 上传图片的接口地址 try { String result = HttpUtil.uploadImage(url, imageBytes); System.out.println(result); } catch (IOException e) { e.printStackTrace(); } ``` 注意:代码中使用了Apache HttpClient库,需要将其添加到项目依赖中。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值