java - 在获取请求中传递名称中带有空格的文件名
问题描述
我有一个文件的两个副本。一个是 CatBoarding.mp4,另一个是 Cat Boarding.mp4
当我执行时:http://localhost:8080/VT/Pages/jspDynamic/dynamic.jsp?video=CatBoarding.mp4
in chrome in 工作正常。
但是,当我尝试:
http://localhost:8080/VT/Pages/jspDynamic/dynamic.jsp?video="Cat Boarding.mp4"
http://localhost:8080/VT/Pages/jspDynamic/dynamic.jsp?video='Cat Boarding.mp4'
http://localhost:8080/VT/Pages/jspDynamic/dynamic.jsp?video=Cat Boarding.mp4
http://localhost:8080/VT/Pages/jspDynamic/dynamic.jsp?video=Cat%20Boarding.mp4
未找到该文件。我确实注意到浏览器在每种情况下都会为空间插入 %20
@the_storyteller 发现问题不在于我如何将参数传递给 jsp,而在于我如何在 jsp 中使用参数。原来我们在jsp文件里面有:
<source src= <%= "../../videos/" + video %> type='video/mp4'>
这最终看起来像:
<source src= videos/Cat Boarding.mp4 type='video/mp4'>
有两种简单的修复方法:
video = video.replace(" ","%20");
在jsp文件中添加或改变
<source src= <%= "'../../videos/" + video + "'" %> type='video/mp4'>
解决方案
抱歉,如果我不明白您为什么将此问题标记为 java 问题,希望这会有所帮助:
请记住,URL/URN 中的“空格”被视为不安全字符。RFC1630说:
There is a conflict between the need to be able to represent many
characters including spaces within a URI directly, and the need to
be able to use a URI in environments which have limited character
sets or in which certain characters are prone to corruption. This
conflict has been resolved by use of an hexadecimal escaping
method which may be applied to any characters forbidden in a given
context. When URLs are moved between contexts, the set of
characters escaped may be enlarged or reduced unambiguously.
The use of white space characters is risky in URIs to be printed
or sent by electronic mail, and the use of multiple white space
characters is very risky. This is because of the frequent
introduction of extraneous white space when lines are wrapped by
systems such as mail, or sheer necessity of narrow column width,
and because of the inter-conversion of various forms of white
space which occurs during character code conversion and the
transfer of text between applications. This is why the canonical
form for URIs has all white spaces encoded.
所以我想如果你需要在你的代码中使用“有风险”或“不明确”的 URI,只需用它们的百分比编码代码替换有风险的字符(%20 代表空格,%3C 代表“<”等)
解决此问题的另一种方法是在您的情况下保存您的视频文件,其名称更安全,称为“slug”,用户和系统(如搜索引擎或 http 客户端)更容易阅读。
例如,法语标题使用可能导致相同问题的字符(é、è、î、à、ç 等)。使用 slug,您可以在将文件保存到服务器之前更改文件,所有“空格”都会出现您选择的字符(例如“-”或“_”)。
java中的Slugify(com.github.slugify)可以帮助你做到这一点
推荐阅读
- python - 如何使用 selenium python 将属性更改为随机数
- java - Java Stream:如何从 json 中找到 id?
- c++ - 如何在 C++ 中连接 char*?
- java - 如何在 Flutter 中将意图传递给方法通道
- node.js - 使用 axios 和 nodejs 处理 Redux Actions 中的错误对象
- python - 数据框列的 cumcount 反向
- c++ - 如何在 C++ 中存储动态创建的对象的地址?
- python - 从图像标签创建边界框
- git - 如何在 github 上恢复提交历史记录?
- three.js - 如何修复用于宽 FOV 显示的 Threejs webxr 示例?