2012-04-16 176 views
0

我有一個瀏覽按鈕,我將它保存到數據庫。mvc3獲取完整路徑使用HttpPostedFileBase

使用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測試,它的工作。所以我錯過了傳遞給函數的完整路徑...。

如何從用戶選擇的瀏覽按鈕中獲取完整路徑。

謝謝,

+0

使用的MemoryStream類工作: http://stackoverflow.com/questions/7852102/convert- httppostedfilebase-to-byte – Ben 2012-04-16 19:36:36

回答

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(); 
    } 
} 

對於​​擴展方法看到此鏈接:

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

+0

當我嘗試將文件轉換爲位圖時,我得到 異常詳細信息:System.ArgumentException:參數無效。 我使用的代碼:var i = new Bitmap(filefullpath);任何想法爲什麼?當我提供完整路徑的時候,我做錯了什麼? thx – Ben 2012-04-16 15:58:36

+0

還是有更好的方式保存數據庫中的文件? – Ben 2012-04-16 16:04:18