将物理路径转换为相对于 http://localhost 的相对路径:
我使用 asp.net 4 和 c#。
我有这段代码可以让我找到图像的物理路径。 正如你所看到的,我得到了我的机器物理 pagh file:///C:。
string pathRaw = HttpContext.Current.Request.PhysicalApplicationPath + "Statics\\Cms\\Front-End\\Images\\Raw\\";
结果:
file:///C:/......../f005aba1-e286-4d9e-b9db-e6239f636e63.jpg
但我需要在 Web 应用程序的前端显示此图像,因此我需要这样的结果:
http://localhost:1108/Statics/Cms/Front-End/Images/Raw/f005aba1-e286-4d9e-b9db-e6239f636e63.jpg
如何做到这一点?
PS:我需要转换变量pathRaw的结果。
希望我能够表达自己的意思,不幸的是我不确定这种情况下的术语。
感谢您的帮助!
I use asp.net 4 and c#.
I have this code that allow me to find the physical path for an image.
As you can see I get my machine physical pagh file:///C:.
string pathRaw = HttpContext.Current.Request.PhysicalApplicationPath + "Statics\\Cms\\Front-End\\Images\\Raw\\";
Result:
file:///C:/......../f005aba1-e286-4d9e-b9db-e6239f636e63.jpg
But I need display this image at the Front end of my web application so I would need a result like this:
http://localhost:1108/Statics/Cms/Front-End/Images/Raw/f005aba1-e286-4d9e-b9db-e6239f636e63.jpg
How to do it?
PS: I need to convert the result of variable pathRaw.
Hope I was able to express myself unfortunately I'm not sure about terminology in this case.
Thanks for your help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
最简单的事情就是摆脱物理应用程序路径。
如果您无法在代码中执行此操作,只需将其从 pathRaw 变量中删除即可。像这样:
代码首先检查路径是否在应用程序根目录内。如果不是,则无法找出该文件的 url,因此会引发异常。
虚拟路径是通过剥离物理应用程序路径、将所有反斜杠转换为斜杠并在路径前添加
"~/"
前缀来构建的,以指示它应该被解释为相对于应用程序根目录。之后,您可以使用 ResolveClientUrl(虚拟路径)。
The easiest thing to do is get rid of the physical application path.
If you cannot do that in your code, just strip it off the pathRaw variable. Like this:
The code first checks to see if the path is within the application root. If not, there's no way to figure out a url for the file so an exception is thrown.
The virtual path is constructed by stripping off the physical application path, convert all back-slashes to slashes and prefixing the path with
"~/"
to indicate it should be interpreted as relative to the application root.After that you can convert the virtual path to a relative path for output to a browser using ResolveClientUrl(virtualPath).
使用 Request.ApplicationPath
然后使用这个问题的答案来获取相对路径。
它可能需要一些调整,但它应该允许您做您想做的事情。
Get the root of your application using Request.ApplicationPath
then use the answer from this question to get a relative path.
It might need a bit of tweaking but it should allow you to do what you're after.
通过 Request.ApplicationPath 左剥离您的路径原始内容并使用
Left-strip your pathRaw content by the Request.ApplicationPath and construct the url using
利用
ApplicationPath
- 获取服务器上 ASP.NET 应用程序的虚拟应用程序根路径。Make use of
ApplicationPath
- Gets the ASP.NET application's virtual application root path on the server.您可以使用 Server.MapPath 来实现此目的。
You can use Server.MapPath for this.