0

我有一个浏览按钮,我将它保存到数据库中。

使用 mvc3

看法

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

控制

public ActionResult Upload(FormCollection collection HttpPostedFileBase file)
      string filefullpath = Path.GetFullPath(file.FileName);

Path.GetFullPath 只返回文件名,我的代码崩溃了,因为它需要完整的文件路径。

我尝试通过通过测试完整路径 C:\filename.jpg 进行测试,并且它有效。所以我错过了要传递给函数的完整路径....

如何从用户选择的浏览按钮中获取完整路径。

谢谢,

4

1 回答 1

0

据我所知,您无法获得完整的路径。它与安全有关。

无论如何,您不需要它,因为您可以将流保存到任何您喜欢的位置。

更新:

一些基本代码:

var file = Request.Files[0];

if (file == null || file.ContentLength == 0)
{
    throw new InvalidOperationException("No file has been selected for upload or the file is empty.");
}

file.SaveAs(path);  // <-- path is somewhere on you *local* drive

或进入数据库:

数据结构

CREATE TABLE [dbo].[SystemImage](
[Id] [uniqueidentifier] NOT NULL,
[ImageData] [image] NOT NULL,
CONSTRAINT [PK_SystemImage] PRIMARY KEY CLUSTERED 
(
[Id] ASC
) WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

ALTER TABLE [dbo].[SystemImage] ADD  CONSTRAINT [DF_SystemImage_Id]  DEFAULT (newid()) FOR [Id]
GO

代码

using (var connection = new SqlConnection(@"data source=.\SQLEXPRESS;initial catalog=ImageTest;Integrated Security=SSPI;"))
{
    connection.Open();

    using (var command = connection.CreateCommand())
    {
        command.CommandType = CommandType.Text;
        command.CommandText = "insert into SystemImage (ImageData) values (@ImageData)";

        command.Parameters.AddWithValue("ImageData", file.InputStream.ToBytes());
        command.ExecuteNonQuery();
    }
}

对于Stream.ToBytes()扩展方法,请参见此链接:

http://shuttle.codeplex.com/SourceControl/changeset/view/3f7f1f2cf2c0#Shuttle.Core%2fsource%2fShuttle.Core.Infrastructure%2fExtensions%2fStreamExtensions.cs

于 2012-04-16T15:32:44.160 回答