0

I have a browse button and I am saving it to the database.

using mvc3

view

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

control

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

the Path.GetFullPath returns just the file name and my code crushes cause it is expecting full file path.

I tried testing by passing test full path C:\filename.jpg and it worked. so I am missing the full path to be passed to the function....

How do I get the full path from the browse button that was selected by the user.

Thanks,

Benk
  • 1,284
  • 6
  • 33
  • 64
  • worked using MemoryStream class: http://stackoverflow.com/questions/7852102/convert-httppostedfilebase-to-byte – Benk Apr 16 '12 at 19:36

1 Answers1

0

As far as I know you cannot get the full path. It has something to do with security.

Anyhow, you do not need it since you will be saving the stream to whever you like.

Update:

Some bare-bones code:

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

or into a database:

Data Structure

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

Code

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

For the Stream.ToBytes() extensions method see this link:

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

Eben Roux
  • 12,983
  • 2
  • 27
  • 48
  • when I try to convert the file to bitmap, I get Exception Details: System.ArgumentException: Parameter is not valid. code I am using: var i = new Bitmap(filefullpath); any ideas why? when I provide full path it works, what I am doing wrong? thx – Benk Apr 16 '12 at 15:58
  • or is there a better way saving the file in the database? – Benk Apr 16 '12 at 16:04