The
FileName
property returns either the name of the file, or the path of the file
on the client, depending on the browser settings. In this case, it looks like you're getting just the name.
Path.GetFullPath
will resolve the path of the file relative to the current path. In this case, the current path is the folder containing the Visual Studio development server.
Server.MapPath
will resolve the path relative to the currently executing page. This is not necessarily the same as the current path used by
GetFullPath
.
You need to save the file in a known location, to which your site must have write access. For example, if you want to save the file in a folder called
images
in the root of your site:
protected void upload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string fileName = Path.GetFileName(FileUpload1.FileName);
string virtualPath = "~/images/" + fileName;
string physicalPath = Server.MapPath(virtualPath);
FileUpload1.SaveAs(physicalPath);
passport1img.ImageUrl = virtualPath;
SaveToDatabase(physicalPath);
}
}
private void SaveToDatabase(string pathToImageFile)
{
byte[] fileBytes = File.ReadAllBytes(pathToImageFile);
...
}
Alternatively, you could skip saving the file to disk, and save it directly to the database:
protected void upload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
int length = (int)FileUpload1.FileContent.Length;
byte[] fileBytes = new byte[length];
FileUpload1.FileContent.Read(fileBytes, 0, length);
SaveToDatabase(fileBytes);
}
}
private void SaveToDatabase(byte[] fileBytes)
{
...
}