S5498658 S5498658 - 2 months ago 11
ASP.NET (C#) Question

Saving Data to Database using fileuploadControl in C#

I have an multiple file upload control inside my form. I am trying to upload as many as files that users wants to database with a dropdown to choose the type of attachment. I am able to save the file to database but I get all 0's for my Data (0x0000000000000000000000000000000000000000...00).
And when I'm trying to retrieve the file when user clicks on the file link, I get an error that syas "Failed to load the pdf document".

Here is my code for saving it to the database:

public void getDynamicFilesFromUploadedFileList(int wWireTransferID, int wUserID)
{
if (GridView1.Rows.Count > 0)
{
foreach (GridViewRow grow in GridView1.Rows)
{
try
{
FileUpload fileuploadControl = new FileUpload();
fileuploadControl = (FileUpload)grow.FindControl("fUpControl");

DropDownList drpFileType = new DropDownList();
drpFileType = (DropDownList)grow.FindControl("ddlFileType");
Guid newID = Guid.NewGuid();

if (fileuploadControl.HasFile)
{
//I believe here is my mistake
Byte[] fileData = new Byte[fileuploadControl.PostedFile.ContentLength];

new MRSManager().InsertWTDocument(wWireTransferID,
fileuploadControl.FileName,
drpFileType.SelectedValue.Trim(),
fileuploadControl.PostedFile.ContentType,
System.IO.Path.GetExtension(fileuploadControl.FileName),
fileuploadControl.PostedFile.ContentLength.ToString(),
fileData,
wUserID,
newID);
}
else
{
string m = "No File! ";
}
}
catch (Exception Exp)
{
string msg = Exp.Message.ToString();
}
}
}
}


enter image description here

And this is the code on How I try to retrieve the file.

protected void Page_Load(object sender, EventArgs e)
{
// Get the file id from the query string
string id = Request.QueryString["ID"];

// Get the file from the database
DataTable file = GetAFile(id);
DataRow row = file.Rows[0];

string name = (string)row["FileName"];
string contentType = (string)row["ContentType"];
Byte[] data = (Byte[])row["Data"];

Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
// Send the file to the browser
Response.AddHeader("Content-type", contentType);
Response.AddHeader("Content-Disposition", "inline; filename=" + name);
Response.Buffer = true;
Response.BinaryWrite(data);
Response.Flush();
Response.Close();
Response.End();
}

// Get a file from the database by ID
public static DataTable GetAFile(string id)
{
DataTable file = new DataTable();
string sSQL = string.Format("SELECT * FROM tblWireTransferDocuments WHERE FileID = '{0}'", id);
file = SqlHelper.ExecuteDataset(DBConnection.GetConnectionString(), CommandType.Text, sSQL, null).Tables[0];
return file;
}
}


}

Answer

You're right

 //I believe here is my mistake
 Byte[] fileData = new Byte[fileuploadControl.PostedFile.ContentLength];

You only created fileData, but didn't fill it. You should use fileuploadControl.PostedFile to fill fileData.

Comments