webserver错误:不是有效的虚拟路径
将网站图片保存到sqlserver数据库,提示“不是有效的虚拟路径”,但文件明明就在那里,路径完全正确,权限也增加了,不知是什么原因。
代码如下:
[WebMethod]
public int savetosql(String filename,String sort, int sort_id, String memo)
{
//String newFile = HttpContext.Current.Server.MapPath("upload/" + filename);
String newFile = Server.MapPath("~/upload") + "\\" + filename;
try
{
//FileStream fs = File.OpenRead(newFile);
FileStream fs = new FileStream(Server.MapPath(newFile), FileMode.Open, FileAccess.Read);
byte[] FileData = new byte[fs.Length];
fs.Read(FileData, 0, FileData.Length);
string constr = ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand com = new SqlCommand("INSERT INTO photo(sort,sort_id,img,memo)"
+ " VALUES (@sort,@sort_id,@img,@memo)", con);
com.Parameters.Add("@img", SqlDbType.Image);
com.Parameters["@img"].Value = FileData;
com.Parameters.Add("@sort", SqlDbType.VarChar);
com.Parameters["@sort"].Value = sort;
com.Parameters.Add("@sort_id", SqlDbType.Int);
com.Parameters["@sort_id"].Value = sort_id;
com.Parameters.Add("@memo", SqlDbType.VarChar);
com.Parameters["@memo"].Value = memo;
try
{
com.ExecuteNonQuery();
fs.Close();
return 0;
}
catch (Exception e)
{
fs.Close();
return -1;
}
}
------解决方案--------------------
String newFile = Server.MapPath("~/upload") + "\\" + filename;
FileStream fs = new FileStream(Server.MapPath(newFile), FileMode.Open, FileAccess.Read);
你怎么进行2次MapPath啊。多余一次
FileStream fs = new FileStream(Server.MapPath(newFile), FileMode.Open, FileAccess.Read);
改成
FileStream fs = new FileStream(newFile, FileMode.Open, FileAccess.Read);