Skip to main content
 首页 » 编程设计

c#之在网络服务器和本地主机上保存和访问文件

2024年02月06日16over140

我想通过我的全功能文件上传控件将文件保存在网络服务器上。我收到了 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(); 它在网络服务器和本地主机上的 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

为了更容易理解,我会给你一个链接到我的应用程序: MyWebsite 要测试它,您必须:

  1. 按类(class)创建标签
  2. 按下按钮 +
  3. 按下选择任何类(class)架构
  4. 点击任意一个彩色div
  5. 从列表中选择文件类型
  6. 上传文件

应该显示您的文件,但实际上没有(主要是 View - 单击的 div)。

我建议使用谷歌浏览器,因为在其他浏览器上您可能会遇到一些视觉问题。

请您参考如下方法:

您必须将文件存储在提供的路径内的任何位置,然后使用 FileResult 操作结果使用操作来检索该文件

public FileResult file(string fileName) 
{ 
    return File(Path.Combine(Path.GetTempPath(), fileName), System.Net.Mime.MediaTypeNames.Application.Octet); 
} 

这不是完整的解决方案,但应该能让您走上正轨。