尝试将文件名添加到字符串结尾时出错:
if (FileUploadControl.HasFile)
{
try
{
string theUserId = Session["UserID"].ToString();
OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;");
cn.Open();
string filename = Path.GetFileName(FileUploadControl.FileName);
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/") + filename);
// error on this line filename only assignment, call can be used as a statement
FileUploadControl.SaveAs(Server.MapPath(fileuploadpath));
StatusLabel.Text = "Upload status: File uploaded!";
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES ('" + theUserId + "' , '" + fileuploadpath + "')", cn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
}
如果我这样试试:
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/");
FileUploadControl.SaveAs(Path.Combine(fileuploadpath, filename));
我得到一个mysql错误,因为没有文件名添加到路径的末尾(顺便说一句,我只是试图保存路径而不是图像)从技术上讲,我仍然可以将半个文件路径插入到sql中,所以也许这样使用上面的代码错误与我的原始上传方法无关。但显然我仍然需要完整的路径名。
无法上传文件。发生以下错误:错误[42000] [MySQL] [ODBC 3.51驱动程序] [mysqld-5.5.9]您的SQL语法中有错误;检查与MySQL服务器版本对应的手册,以便在第1行的“C:\ Users \ Garrith \ Documents \ Visual Studio 2010 \ WebSites \ WebSite1 \ userdata \ 1 \ uplo”附近使用正确的语法
答案 0 :(得分:1)
您在同一个字符串上使用Server.MapPath两次。请从任何位置删除它,以便根据服务器映射的路径可能不会再次映射。
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/") + filename);
FileUploadControl.SaveAs(Server.MapPath(fileuploadpath));
你可以这样做......
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/") + filename);
FileUploadControl.SaveAs(fileuploadpath);
答案 1 :(得分:0)
您收到此错误,因为您路径中的第一个字符是〜。您要做的是尝试删除此字符,然后将字符串保存在数据库中。
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES ('" + theUserId + "' , '" + fileuploadpath.Substring(1,fileuploadpath.Length - 1) + "')", cn);
答案 2 :(得分:0)
它可以设法自己做到这一点:
//string filename = Path.GetFileName(FileUploadControl.FileName);
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/") + Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(fileuploadpath);
StatusLabel.Text = "Upload status: File uploaded!";
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES ('" + theUserId + "' , '" + fileuploadpath + "')", cn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
}