java 从 Content-Disposition 获取文件名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27226258/
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
Get filename from Content-Disposition
提问by h2c
I'm uploading a blob file from an HTML form to a database using JSP. I need to insert the filename into DB. I know that the filename is stored in the Content-Disposition header, how could I get that?
我正在使用 JSP 将 Blob 文件从 HTML 表单上传到数据库。我需要将文件名插入数据库。我知道文件名存储在Content-Disposition 标头中,我怎么能得到它?
回答by Joop Eggen
If you uploaded the file using JavaEE 6 with HttpServletRequest.getPart
:
如果您使用 JavaEE 6 上传文件HttpServletRequest.getPart
:
Part part = request.getPart("xxx"); // input type=file name=xxx
String disposition = part.getHeader("Content-Disposition");
String fileName = disposition.replaceFirst("(?i)^.*filename=\"?([^\"]+)\"?.*$", "");
See Part.
见部分。
As @Marc mentioned I did not treat URL encoding. (He also made the quotes around the filename optional.)
正如@Marc 提到的,我没有处理 URL 编码。(他还将文件名周围的引号设为可选。)
fileName = URLDecoder.decode(fileName, StandardCharsets.ISO_8859_1);
Not checked, but HTTP encoding for headers should be the default ISO-8859-1.
未选中,但标头的 HTTP 编码应为默认 ISO-8859-1。