gpt4 book ai didi

c# - 如何在使用 Razor 将文件上传到 MVC 3 中的 App_Data/Uploads 后查看文件?

转载 作者:太空狗 更新时间:2023-10-29 22:08:29 24 4
gpt4 key购买 nike

我是 mvc 的新手,但遇到了一个问题。我到处寻找答案,但找不到,但我很确定有什么东西跳过了我。问题是我不知道如何在将文件上传到 App_Data 文件夹后访问文件。我使用在所有论坛上找到的相同代码:

我认为我使用这个

@using (Html.BeginForm("Index", "Home", FormMethod.Post, 
new { enctype="multipart/form-data" }))
{
<input type="file" name="file" />
<input type="submit" value="submit" />
}

对于我的 Controller ,我使用这个

public class HomeController : Controller
{
// This action renders the form
public ActionResult Index()
{
return View();
}

// This action handles the form POST and the upload
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
// Verify that the user selected a file
if (file != null && file.ContentLength > 0)
{
// extract only the fielname
var fileName = Path.GetFileName(file.FileName);
// store the file inside ~/App_Data/uploads folder
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
// redirect back to the index action to show the form once again
return RedirectToAction("Index");
}
}

我的模型是

public class FileDescription
{
public int FileDescriptionId { get; set; }
public string Name { get; set; }
public string WebPath { get; set; }
public long Size { get; set; }
public DateTime DateCreated { get; set; }
}

问题是我想将文件上传到数据库,然后将 WebPath 作为我文件的链接。我希望我说得够清楚了。任何帮助将不胜感激。谢谢

最佳答案

您可以访问文件服务器端(以便从 ASP.NET 应用程序访问其内容)- 只需使用 Server.MapPath("~/App_Data/uploads/<yourFileName>")获取绝对路径(例如 C:/inetpub/wwwroot/MyApp/Add_Data/MyFile.txt)。

出于安全原因,

无法通过 URL 直接访问 App_Data 文件夹的内容。所有配置、数据库都存储在那里,所以原因很明显。如果您需要通过 URL 访问上传的文件 - 将其上传到其他文件夹。

我想您需要可以通过网络访问该文件。在这种情况下,最简单的解决方案是将文件名(或开头提到的完整绝对路径)保存到数据库中的文件,并创建一个 Controller 操作,该操作将采用文件名并返回文件的内容。

关于c# - 如何在使用 Razor 将文件上传到 MVC 3 中的 App_Data/Uploads 后查看文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7302253/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com