1

我正在使用mvc 2010 Express在c#中创建一个应用程序,并且在某些时候,用户可以上传文件并将其打开/下载到/从数据库中。 这是我存储文件的表:

CREATE TABLE [dbo].[tClientsFiles](  
    [IdClient] [int] NOT NULL,  
    [IdFile] [int] IDENTITY(1,1) NOT NULL,  
    [Name] [varchar](256) NULL,  
    [Type] [varchar](256) NULL,  
    [Lenght] [money] NULL,  
    [Content] [varbinary](max) NULL,  
    [DateAdd] [datetime] NULL,  
    [UserAdd] [varchar](50) NULL)  

在 tClientsFiles.Name 中,我将文件的路径和名称存储为:,uploadFile.FileName;其中. 因此,例如,如果文件在并且它在用户的桌面中,它存储uploadFileHttpPostedFileBaseTest.txtC:\Users\user\Desktop\test.txt

然后,在查看/下载文件时,我有一个指向我的ActionResult链接Controller

public ActionResult GetFile(int id)
    {
        var file = dre.tClientsFiles.First(m => m.IdFile == id);

        MemoryStream ms = new MemoryStream(file.Content, 0, 0, true, true);
        Response.ContentType = file.Type;
        Response.AddHeader("content-disposition", "attachment;filename=" + file.Name);
        Response.Buffer = true;
        Response.Clear();
        Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
        Response.OutputStream.Flush();
        Response.End();
        return new FileStreamResult(Response.OutputStream, file.Type);
    }

打开文件时,它用它的 "Name" 命名它file.Name,如下所示:c_Users_user_Desktop_Test.

My question is: is there a way (maybe modifying my Response.AddHeader) to name it with just its "real name"? (I mean, in our example: Test)
Or maybe a way to store the Name in a different way so that it just stores its "real name" instead of the name and its whole path?

Thanks a lot for your time!

4

2 回答 2

2

Try

Response.AddHeader("content-disposition", "attachment;filename=" + Path.GetFileName(file.Name));
于 2013-02-05T16:12:03.873 回答
1

If you want the file name without the extension ie the .txt bit then

Response.AddHeader("content-disposition", "attachment;filename=" + Path.GetFileNameWithoutExtension(file.Name));

Path is in the System.IO namespace.

于 2013-02-05T16:16:45.980 回答