spring 如何使用inputStream获取文件名和文件类型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13230513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get file name and file Type using inputStream?
提问by Arunprasad
guys i'm using inputStream for file Download . now i want to pass fileName and fileType into DefaultStreamedContent .now how can i find fileName and FileType using inputStream .
伙计们,我正在使用 inputStream 进行文件下载。现在我想将 fileName 和 fileType 传递到 DefaultStreamedContent 中。现在我如何使用 inputStream 找到 fileName 和 FileType 。
InputStream inputStream = new BufferedInputStream(new FileInputStream(filePath));
fileDownload = new DefaultStreamedContent(inputStream,**fileType,fileName**);
回答by BalusC
This information can't be extracted from InputStream. This information can only be extracted based on the filePath(and with little help of java.io.Fileto easily get the filename).
无法从 中提取此信息InputStream。此信息只能根据filePath(并且几乎没有帮助java.io.File来轻松获取文件名)提取。
File file = new File(filePath);
InputStream inputStream = new FileInputStream(file);
String fileName = file.getName();
String fileType = FacesContext.getCurrentInstance().getEexternalContext().getMimeType(fileName);
fileDownload = new DefaultStreamedContent(inputStream, fileType, fileName);
The ExternalContext#getMimeType()is determined based on <mime-mapping>entries in web.xml. The servletcontainer has already a whole bunch definied by itself (in Tomcat, check /conf/web.xml) but you can extend and override it by (re)defining them in webapp's own /WEB-INF/web.xmllike as follows for an XLSX type:
在ExternalContext#getMimeType()基于确定<mime-mapping>的条目web.xml。servletcontainer 已经自己定义了一大堆(在 Tomcat 中, check /conf/web.xml),但是您可以通过(重新)在 webapp 自己中定义它们来扩展和覆盖它,/WEB-INF/web.xml如下所示,对于 XLSX 类型:
<mime-mapping>
<extension>xlsx</extension>
<mime-type>application/vnd.openxmlformats-officedocument.spreadsheetml.sheet</mime-type>
</mime-mapping>

