从过去 10 天开始,我尝试了很多在网络中提供的方法/示例/教程来解决我的问题。但是,对于所有这些情况,我都失败了。 我想上传特定/多个产品的图片,将它们保存在数据库中,并通过调用它们的 ID 在首页中显示它们。谁能为此给我逐步示例/教程/链接。 请不要给出部分答案/建议。因为我已经厌倦了这些。
最佳答案
我刚刚解决了我的问题,这里是解决方案:
这是我的模型类
public class Picture
{
public int PictureId { get; set; }
public IEnumerable<HttpPostedFile> Image { get; set; }
public string Name { get; set; }
public long Size { get; set; }
public string Path { get; set; }
}
这是我的 Controller
[HttpPost]
public void Upload() //Here just store 'Image' in a folder in Project Directory
// name 'UplodedFiles'
{
foreach (string file in Request.Files)
{
var postedFile = Request.Files[file];
postedFile.SaveAs(Server.MapPath("~/UploadedFiles/") + Path.GetFileName(postedFile.FileName));
}
}
public ActionResult List() //I retrive Images List by using this Controller
{
var uploadedFiles = new List<Picture>();
var files = Directory.GetFiles(Server.MapPath("~/UploadedFiles"));
foreach(var file in files)
{
var fileInfo = new FileInfo(file);
var picture = new Picture() { Name = Path.GetFileName(file) };
picture.Size = fileInfo.Length;
picture.Path = ("~/UploadedFiles/") + Path.GetFileName(file);
uploadedFiles.Add(picture);
}
return View(uploadedFiles);
}
这是我的“索引” View
@using(Html.BeginForm("Upload", "Picture", FormMethod.Post,
new { enctype="multipart/form-data" })){
<div>
Select a file: <input type="file" name="fileUpload" />
<input type="submit" value="Upload" />
</div> }
通过这个“列表” View ,我显示了图像列表:
<table>
<tr>
<td> Name </td>
<td> Size </td>
<td> Preview </td>
</tr>
@foreach (var file in Model)
{
<tr>
<td> @file.Name </td>
<td> @file.Size </td>
<td>
<img src="@Url.Content(file.Path)"/>
</td>
</tr>
}
关于c# - 使用 Code First 方法中的 Id 从数据库上传、保存和检索图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23517615/