ASP.NET保留上传的文件名

Sib*_*Guy 2 .net asp.net asp.net-mvc file-upload

我想保留上传的文件名,以便用户可以使用相同的名称下载文件.但是我该如何实现呢?我看到的一个选项是将每个文件存储到具有唯一名称的文件夹(例如,GUID).还有其他选择吗?

Dar*_*rov 5

上传文件时,您可以提取其名称:

[HttpPost]
public ActionResult Index(HttpPostedFileBase file) 
{
    if (file != null && file.ContentLength > 0) 
    {
        // Get the filename of the uploaded file
        var fileName = Path.GetFileName(file.FileName);
        var savedFilename = Guid.NewGuid().ToString();

        // TODO: Associate the fileName with the savedFilename
        // and probably the currently connected user in the database

        // Save the file inside the Uploads folder
        var path = Path.Combine(Server.MapPath("~/Uploads"), savedFilename);
        file.SaveAs(path);
    }
    return RedirectToAction("Index");
}
Run Code Online (Sandbox Code Playgroud)

您可以使用某个唯一名称将文件存储在磁盘上(GUID是一个不错的选项),然后将此唯一名称与实际文件名和用户相关联,以便以后当他想要下载文件时,您将拥有映射.