gpt4 book ai didi

c# - 使用 Code First 方法中的 Id 从数据库上传、保存和检索图像

转载 作者:太空狗 更新时间:2023-10-30 00:52:05 27 4
gpt4 key购买 nike

从过去 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com