在项目中有这么一个需求:判断上传文件的类型,考虑两种方案:
1. 通过正则表达式从文件名中获取;
2. 使用URLConnection.guessContentTypeFromStream通过文件前16个字节推断;
第一种方法显然不够严谨(文件名可随意更改),于是采用 了第二种方案
// some code FileInputStream inputFile = new FileInputStream("D:/test.pdf"); String mime = URLConnection.guessContentTypeFromStream(inputFile); // save to mongodb......
一周后,偶然发现所有上传的文件在mongo中mine字段均为空,翻读guessContentTypeFromStream方法源码有一处判断引起了我的注意:
markSupported ? 似有所悟,翻阅JDK文档后一切拨云见日:
markSupported public boolean markSupported() Tests if this input stream supports the mark and reset methods. Whether or not mark and reset are supported is an invariant property of a particular input stream instance. The markSupported method of InputStream returns false. Returns: true if this stream instance supports the mark and reset methods; false otherwise. See Also: mark(int), reset()
首先介绍一下InputStream类提供的mark与reset方法:
在该输入流中使用mark标记当前位置,后续调用 reset 方法重新将流定位于最后标记位置,以便后续读取。
markSupported方法可以判断当前类是否具有mark与reset方法的能力,只有重写了mark与reset方法,markSupported才会返回true。前面展示的代码使用的FileInputStream没有重写父类InputStream的这两个方法,其不具有mark和reset方法的能力,使用BufferInputStream替换FileInputStream可解决此问题:
FileInputStream inputFile = new FileInputStream("D:/t1.png"); System.out.println("FileInputStream mime:" + URLConnection.guessContentTypeFromStream(inputFile)); System.out.println("BufferedInputStream mime:" + URLConnection.guessContentTypeFromStream(new BufferedInputStream(inputFile))); print result: FileInputStream mime:null BufferedInputStream mime:image/png
相关推荐
InputStream inputStream= urlConnection.getInputStream(); //4.获取文件格式 String format= "MP4"; if (format.equalsIgnoreCase("mp4")) { response.addHeader("Content-Type","video/mp4;cahrset:...
URL的openConnection()方法将返回一个URLConnection对象,该对象表示应用程序和URL之间的通信连接。程序可以通过URLConnection实例向该URL发送请求,读取URL引用的资源。 程序Demo示范了如何向Web站点发送GET请求、...
使用URLCONNECTION对象访问远程文件
22-网络编程(URL-URLConnection).avi
* 使用URLConnection下载文件或图片并保存到本地。 * * @author 老紫竹(laozizhu.com) */ public class URLConnectionDownloader { public static void main(String[] args) throws Exception { ...
okhttp-urlconnection-3.4.1.jar okhttp-urlconnection okhttp-urlconnection-3.4.1.jar下载
okhttp-urlconnection:3.10.0
一个通过Socket或URLConnection传文件的示例 Socket URLConnection 文件传输
JAVA 根据Url 接口 获取文件名称和类型,亲测可用。输入参数地址即可。
使用URL和URLConnection(多线程下载)
NULL 博文链接:https://bijian1013.iteye.com/blog/2299735
HttpClient4.5版本所需的全部jar包,HttpClient相比传统JDK自带的URLConnection增加了易用性和灵活性
8.5 将网络图像网址放入Gallery中显示——URL.URLConnection.BaseAdapter 8.6 即时访问网络图文件展示——HttpURLConnection 8.7 手机气象局,实时卫星云图——HttpURLConnection与URLConnection和运行线程 8.8 通过...
。。。
自定义拦截器,使用URLConnection.setContentHandlerFactory(new ContentHandlerFactoryImpl());方法,把自定义的ContentFactory(拦截器)替换原来的方法,这样getContent方法返回的将是已经处理好的对象。 应当注意...
java URLConnection 的详细介绍,牛人项目经验的总结,绝对通俗易懂,包括cookie操作,上传文件,以及下载网页等介绍,是非常难得文档和教材
URLConnection和HttpClient使用入门
URL以及URLConnection的使用
4. 2 Servlet向客户端返回MIME类型 4. 3 在服务器瑞生成统计图形 4. 3. 1 产生图形 4. 3. 2 产生条形图 4. 3. 3 产生饼形图 4. 3. 4 将绘制的图形转化成JPEG格式 4. 3. 5 在服务器端产生条形图和饼形图的实例...