使用C#中的fileuploadControl将数据保存到数据库#
问题描述:
我在窗体中有多个文件上传控件。我试图上传尽可能多的用户想要数据库的文件,并用下拉菜单选择附件的类型。我能够将文件保存到数据库,但我的数据全部为0(0x0000000000000000000000000000000000000000 ... 00)。 当我试图检索文件,当用户点击文件链接时,我得到一个错误,syas“无法加载PDF文档”。使用C#中的fileuploadControl将数据保存到数据库#
这里是我的代码它保存到数据库:
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();
}
}
}
}
这是我如何尝试检索该文件的代码。
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;
}
}
}
答
你说得对
//I believe here is my mistake
Byte[] fileData = new Byte[fileuploadControl.PostedFile.ContentLength];
你只创建FILEDATA,但没有填充它。你应该使用fileuploadControl.FileContent来填充fileData。
检查此问题http://*.com/questions/2579373/saving-any-file-to-in-the-database-just-convert-it-to-a-byte-array – DanielVorph