我使用以下代码使用实体框架将我的文件保存到数据库但是由于某种原因它给了我错误:
' C:/ Users / David Buckley / Documents / Visual Studio 2012 / Sis / StudentInformationSystem / admin / uploads /'是物理路径,但预计会有虚拟路径。 描述:执行当前Web请求期间发生未处理的异常。请查看堆栈跟踪,以获取有关错误及其在代码中的起源位置的更多信息。
异常详细信息:System.Web.HttpException:' C:/ Users / David Buckley / Documents / Visual Studio 2012 / Sis / StudentInformationSystem / admin / uploads /'是物理路径,但预计会有虚拟路径
但它似乎将数据库中的文件保存为C:\ Users \ David Buckley \ Documents \ Visual Studio 2012 \ Sis \ StudentInformationSystem \ admin \ uploads \ test.jpg的路径和文件名,但是我可以信服我如果我想将它加载到图像控件imageurl字段属性中,需要以不同方式保存它吗?
try
{
int id = Convert.ToInt32(Request.QueryString["id"]);
if (id == -1) // we neeed a new record otherwise get the old one;
{
Student studentRecord = new Student();
_db.AddStudent(studentRecord);
_db.SaveChanges();
newRecordId = studentRecord.Student_ID;
Session["recordid"] = id;
_student = _db.GetStudentById(newRecordId);
}else
_student = _db.GetStudentById(id);
photoUpload.TargetFolder= Server.MapPath("~/admin/uploads/");
string fullPath = Server.MapPath( "~/admin/uploads/");
photoUpload.OverwriteExistingFiles = true;
string newFileName = "";
foreach (UploadedFile file in photoUpload.UploadedFiles)
{
string fileName = "test";
newFileName =fileName + file.GetExtension();
file.SaveAs(Path.Combine(fullPath, newFileName));
// impelement your database insert here...
}
string thumbPath;
thumbPath = ("~/images" + "/" + newFileName);
_student.Image = thumbPath;
_student.Student_Name = txtStudentName.Text;
_student.Student_FatherName = txtFathersName.Text;
_student.Registration_no = txtRegistrationNo.Text;
_student.Address1 = txtAddress1.Text.Trim();
_student.Address2 = txtAddress2.Text.Trim();
_student.Address3 = txtAddress3.Text.Trim();
_student.RelationWithGuadian = txtRelationshipGurdan.Text.Trim();
_student.GurdianName = txtGurdianName.Text.Trim();
_student.LastSchoolAtten = txtLastSchool.Text.Trim();
_student.Contact1 = txtContact1.Text.Trim();
_student.Contact2 = txtContact2.Text.Trim();
_student.DOB = rdDOB.SelectedDate.Value;
_db.SaveChanges();
}
catch (Exception ex)
{
}
答案 0 :(得分:0)
要从Web应用程序访问该文件,您需要使用虚拟路径。但是您要保存数据库中文件的物理路径。您应该保存Path.Combine(fullPath, newFileName)
的值,而不是将"~/admin/uploads/" + newFileName
的值保存在数据库中。
只要您的uploads/
目录是应用程序目录的后代,上述操作就会起作用。或者,您可以通过显式添加虚拟目录来使用指向应用程序路径之外的目录的路径。