嘿伙计我有问题我上传图片到我的项目路径图像包含在〜/ userdata / UserID / uploadedimage / image.jpg
我使用以下方法上传并在我的数据库中存储图片的路径。
protected void UploadButton_Click(object sender, EventArgs e)
{
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/") + 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;
}
}
}
}
我发现路径不是我项目目录的路径奇怪的东西:
这是我数据库中的一个片段,第一个idPictures = 1是我需要的正确路径名。
idPictures = 2是fileupload插入我的数据库的那个?
我怎样才能得到它所以它会给出一个这样的路径名:
~/userdata/2/uploadedimage/batman-for-facebook.jpg
修改
如果我试试这个:
string fileuploadpath = ("~/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;
}
}
}
}
我收到错误:
无法上传文件。发生以下错误:SaveAs方法配置为需要根路径,路径'〜/ userdata / 1 / uploadedimage / holypally.jpg'不是root。
答案 0 :(得分:1)
我怀疑它将反斜杠视为SQL语句中的转义字符。不要忘记,您正在使用Server.MpaPath
- 即您正在尝试查找该文件的Windows绝对文件名。
这正是您不使用参数化SQL语句时会发生的事情,而是直接在SQL中包含用户指定的文本。 不要这样做。使用参数化SQL命令,单独指定值,然后您至少不需要担心不稳定的值。
当然,您仍然需要确定是否想要存储已翻译的路径,但这是另一回事。
答案 1 :(得分:0)
为了回答我自己的问题,我必须创建两个字符串,一个纯粹用于fileupload,另一个纯粹用于数据库路径名存储:
string filenameDB = Path.GetFileName(FileUploadControl.FileName);
string fileuploadpath = Server.MapPath("~/userdata/"+theUserId+"/uploadedimage/")+Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(fileuploadpath);
string fileuploadpaths = ("~/userdata/"+theUserId+"/uploadedimage/")+filenameDB;
StatusLabel.Text = "Upload status: File uploaded!";
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES ('"+theUserId+"','"+fileuploadpaths+"')", cn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
}