在Web服务器和本地主机上保存和访问文件
本文关键字:保存 访问 文件 主机 Web 服务器 | 更新日期: 2023-09-27 18:07:06
我想通过我的完全工作的文件上传控件在Web服务器上保存一个文件。我已经收到HttpPostedFile file = HttpContext.Current.Request.Files[0];
,我想把它保存在我的服务器上。
我的服务器名为"appharbor"(https://appharbor.com/(,它的规范说,我有Path.getTempPath();
文件夹的文件写入权限。
我保存文件的代码是:
HttpPostedFile file = HttpContext.Current.Request.Files[0];
string dirrectoryPath =Path.GetTempPath();
string fileName = Path.GetFileName(file.FileName);
string mapPath = HttpContext.Current.Server.MapPath(dirrectoryPath);
Directory.CreateDirectory(mapPath);
string fileFullPath = Path.Combine(mapPath, fileName);
file.SaveAs(fileFullPath);
myModel.uri = fileFullPath;
如何以工作的方式重新制作此代码?
视图:
String pdf = "http://docs.google.com/gview?url=" + @Model.uri + "&embedded=true";
<iframe src="@pdf" style="width:100%; height: 1000px;" frameborder="0"></iframe>
正如你所看到的,我们只是试图在网页上显示文件。不允许用户下载(但没有特殊限制(
编辑
详细信息现在发生了什么,略有变化:
当我有时
string dirrectoryPath = Path.GetTempPath();
然后发生在服务器上:
POST http://warsztatynet.apphb.com/api/upload 500 (Internal Server Error)
并且发生在本地
An exception of type 'System.Web.HttpException' occurred in System.Web.dll but was not handled in user code
Additional information: 'C:/Users/Tunczyk/AppData/Local/Temp/' expected virtual path.
我怀疑它们是完全一样的,因为这两者发生在同一个函数中。
Path.GetTempPath();
在Web服务器和localhost 上的App_Data文件夹
当我有时
string dirrectoryPath ="~/App_Data";
然后发生在服务器上:
GET http://c/Users/MyPath/sample.rtf 404 (Not Found)
并且发生在本地:
GET http://c/Users/MyPath/sample.rtf 404 (Not Found)
编辑2这是对Caótico fanegas帖子的回答:
Not allowed to load local resource: file:///D:/Users/apphb5dac91d9317868/AppData/Local/Temp/glyphicons-halflings.png
这就是当我这样做时会发生的事情:
string dirrectoryPath = Path.GetTempPath();
string fileName = Path.GetFileName(file.FileName);
Directory.CreateDirectory(dirrectoryPath);
string fileFullPath = Path.Combine(dirrectoryPath, fileName);
file.SaveAs(fileFullPath);
伙计们,我正在寻找最简单的方法。它不是商业应用。这只是为了上大学。
编辑3
为了更容易理解,我会给你一个我的申请链接:我的网站要测试它,您必须:
- 按"课程创建"选项卡
- 按下按钮+
- 按任意课程模式
- 按下任何彩色潜水器
- 从列表中选择文件类型
- 上载文件
应该显示Your文件,但它没有(主要是视图点击的div(。
我建议使用谷歌浏览器,因为在其他浏览器上你可能有一些视觉问题。
您必须将文件存储在所提供路径内的任何位置,然后使用FileResult操作结果使用操作来检索该文件
public FileResult file(string fileName)
{
return File(Path.Combine(Path.GetTempPath(), fileName), System.Net.Mime.MediaTypeNames.Application.Octet);
}
这不是完整的解决方案,但应该会让你走上正轨。
看起来HttpPostedFile.SaveAs()
需要一个虚拟路径来保存文件。如果不通过Server.MapPath()
将其转换为本地路径,则"~/App_data"
方法应该有效。
如果您被迫保存到TempPath(例如权限问题(,我想您可以使用Stream.CopyTo()
方法将文件保存在随机物理路径上。
using (var newFile = System.IO.File.Create("local_path"))
{
fil.InputStream.CopyTo(newFile);
}
这个代码直接来自我的头脑,因此不是100%可靠的。可能需要一些工作。