如何在mvc4中创建指向sql数据库的imageurl链接
大家好,我怎样才能将imageurl插入数据库?插入数据库后,imageurl行显示为空如何在mvc4中创建指向sql数据库的imageurl链接,sql,asp.net-mvc-4,Sql,Asp.net Mvc 4,大家好,我怎样才能将imageurl插入数据库?插入数据库后,imageurl行显示为空 public HttpPostedFileBase ImageURL { get; set; } 我的问题.cshtml <tr> <td colspan="3"> @Html.LabelFor(model => model.ImageURL) @Html.TextBoxFor(model =>
public HttpPostedFileBase ImageURL { get; set; }
我的问题.cshtml
<tr>
<td colspan="3">
@Html.LabelFor(model => model.ImageURL)
@Html.TextBoxFor(model => model.ImageURL, new { type = "file", id="fileupload", name="fileupload" })
@Html.ValidationMessageFor(model => model.ImageURL)
<img src="#" id="imgThumbnail" alt="preview" width="10%" height="15%" />
</td>
实体框架模型应具有映射到数据库中
varbinary(max)
列的byte[]
属性。看起来您当前将其定义为一个字符串,这是错误的。因此:
public class question1
{
public byte[] ImageURL { get; set; }
...
}
然后读取视图模型上的HttpPostedFileBase属性,并将其复制到EF模型上的byte[]
属性:
foreach (QuestionVM0 q1 in qo)
{
int aID = question1.ActivityID.Value;
byte[] imageData = null;
using (MemoryStream target = new MemoryStream())
{
q1.ImageURL.InputStream.CopyTo(target);
imageData = target.ToArray();
}
Models.question1 questionCreate = new question1();
questionCreate.ImageURL = imageData;
db.questions1.Add(questionCreate);
db.SaveChanges();
}
更新: 您似乎只想存储文件在数据库中的位置,而不想存储文件本身。在这种情况下,您应该执行以下操作:
foreach (QuestionVM0 q1 in qo)
{
int aID = question1.ActivityID.Value;
string fileName = Path.GetFileName(q1.ImageURL.FileName);
string path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
q1.ImageURL.SaveAs(path);
Models.question1 questionCreate = new question1();
questionCreate.ImageURL = path;
db.questions1.Add(questionCreate);
db.SaveChanges();
}
您好,但我的数据库表是varchar(255),我不能使用varbinary(max),我只想存储到数据库的url链接,然后您应该将上载的文件存储在文件系统的某个位置,然后只在数据库中存储此文件的路径。我已经更新了我的答案,以说明你是如何做到这一点的。
foreach (QuestionVM0 q1 in qo)
{
int aID = question1.ActivityID.Value;
string fileName = Path.GetFileName(q1.ImageURL.FileName);
string path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
q1.ImageURL.SaveAs(path);
Models.question1 questionCreate = new question1();
questionCreate.ImageURL = path;
db.questions1.Add(questionCreate);
db.SaveChanges();
}