我将图像上传到数据库并将名称和路径存储在数据库中,但实际图像存储在文件夹中。我已成功将它们存储在文件夹中,但它没有将有关图像的信息保存到数据库。
非常感谢任何帮助。下面是我的代码:
private void StartUpLoad()
{
//get the file name of the posted image
string imgName = FileUpload1.FileName.ToString();
//sets the image path
string imgPath = "images/" + imgName;
//then save it to the Folder
FileUpload1.SaveAs(Server.MapPath(imgPath));
//get the size in bytes that
int imgSize = FileUpload1.PostedFile.ContentLength;
//validates the posted file before saving
if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "")
{
if (FileUpload1.PostedFile.ContentLength > 5120) // 5120 KB means 5MB
{
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Alert", "alert('File is too big')", true);
}
else
{
//save the file
//Call the method to execute Insertion of data to the Database
ExecuteInsert(imgName, imgSize, imgPath);
Response.Write("Save Successfully!");
}
}
}
private string GetConnectionString()
{
//sets the connection string from your web config file. "DBConnection" is the name of your Connection String
return System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
}
private void ExecuteInsert(string name, int size, string path)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "INSERT INTO ImageInfo (ImageName, ImageSize, ImagePath) VALUES "
+ " (@ImgName,@ImgSize,@ImgPath)";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter[] param = new SqlParameter[3];
param[0] = new SqlParameter("@ImgName", SqlDbType.NVarChar, 50);
param[1] = new SqlParameter("@ImgSize", SqlDbType.BigInt, 9999);
param[2] = new SqlParameter("@ImgPath", SqlDbType.VarChar, 50);
param[0].Value = name;
param[1].Value = size;
param[2].Value = path;
for (int i = 0; i < param.Length; i++)
{
cmd.Parameters.Add(param[i]);
}
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
}
finally
{
conn.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
StartUpLoad();
}
以下是我的asp.net代码
<div>
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<asp:Button ID="Button1" runat="server" Text="Save" onclick="Button1_Click" />
</div>
答案 0 :(得分:0)
您的图片路径和名称仅设置为允许50个字符,并且您的图片路径和名称很可能比此长。检查调试中这些值的大小。如果它们超过50个字符,则数据库拒绝插入。
答案 1 :(得分:-1)
为什么不调试代码,将insert命令复制/粘贴到数据库管理器中,看看它是否会引发异常。