简体   繁体   English

如何在数据库中上传文件并在ASP.Net MVC 5中显示它们

[英]How to upload file in database and display them in ASP.Net MVC 5

I am a beginner in ASP.Net MVC 5 and I want to know how to upload file in database and the display them to the user. 我是ASP.Net MVC 5的初学者,我想知道如何在数据库中上传文件并将其显示给用户。 I saw numerous example on internet related to above question. 我在互联网上看到了许多与上述问题有关的例子。 But all talks about putting file in some solution folder. 但是所有人都在谈论将文件放在某个解决方案文件夹中。 But I want to upload file to database and be able to retrieve it in "Details View". 但是我想将文件上传到数据库,并能够在“详细信息视图”中检索它。

Issue: I am able to upload file in Database, but I am not sure how to Display the file link to user. 问题:我可以在数据库中上载文件,但是我不确定如何向用户显示文件链接。 Clicking on which user should be able to view/download the uploaded file. 单击哪个用户应该能够查看/下载上载的文件。 Below is my attempt. 以下是我的尝试。

Model: 模型:

public class File
{
    public int Id { get; set; }
    [StringLength(255)]
    public string FileName { get; set; }
    public byte[] Content { get; set; }
}

Controller: 控制器:

// GET: FileUpload
public ActionResult Create()
{
    return View();
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(File file, HttpPostedFileBase upload)
{
    try
    {
        if (ModelState.IsValid)
        {
            if (upload != null && upload.ContentLength > 0)
            {
                var tempfile = new File
                {
                    FileName = System.IO.Path.GetFileName(upload.FileName),
                };
                using (var reader = new System.IO.BinaryReader(upload.InputStream))
                {
                    tempfile.Content = reader.ReadBytes(upload.ContentLength);
                }
                file.Content = tempfile.Content;
            }
            _context.Files.Add(file);
            _context.SaveChanges();
            return RedirectToAction("Index");
        }
    }
    catch (RetryLimitExceededException /* dex */)
    {
        //Log the error (uncomment dex variable name and add a line here to write a log.
        ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
    }
    return View(file);
}

public ActionResult Details(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    File f1 = _context.Files.Where(f => f.Id == id).SingleOrDefault();
    if (f1 == null)
    {
        return HttpNotFound();
    }
// NOT SURE WHAT TO HERE
    return View(f1);
}

View: Details.chtml file 查看: Details.chtml文件

@model fileupload.Models.File
<h4>File</h4>
@* NOT SURE HOW TO HANDLE THE FILE LINK HERE*@

So, In the database I can see some binary content entry in "Content" Column. 因此,在数据库中,我可以在“内容”列中看到一些二进制内容条目。 But I am not sure how can I display some link in the detail section. 但是我不确定如何在详细信息部分显示一些链接。 I want to display the file link in the details view. 我想在详细信息视图中显示文件链接。 Clicking on which the file will get downloaded or something like preview. 单击下载文件或预览之类的文件。 Kindly guide me. 请指导我。

EDIT 1 编辑1

public FileContentResult Download(int id)
{
    var file = _context.Files.First(f => f.Id == id);
    var fileRes = new FileContentResult(file.Content.ToArray(), "application/pdf");
    fileRes.FileDownloadName = file.FileName;
    return fileRes;
}

Assuming your code in your controller is correctly populating your model, you simply need base64 encode the image and display that. 假设控制器中的代码正确地填充了模型,您只需要对图像进行base64编码并显示出来即可。

@{
    var encodedImage = Convert.ToBase64String(Model.Content);
    var embeddedImage = $"data:image/png;base64,{encodedImage}";
}

<img src="@embeddedImage" />

Take a look at this question as well: MVC How to display a byte array image from model 也看一下这个问题: MVC如何显示模型中的字节数组图像

Add below code in model : 在模型中添加以下代码:

            public string imagePath { get; set; }

            [Display(Description = "imgfile")]
            [RegularExpression(@"([a-zA-Z0-9()\s_\\.\-:!@#$%^&])+(.png|.jpg|.gif|.bmp|.tiff|.PNG|.JPG|.GIF|.BMP|.TIFF)$", ErrorMessage = "Only Image files allowed.")]
            public HttpPostedFileBase imgfile { get; set; }

In controller (This will validate your image for maore than 1mb from your action, if u want to validate it before post you can google it for jquery validations) : 在控制器中(如果您要在发布前验证图像,则可以从您的操作中验证图像是否大于1mb):

if (userRegObj != null && userRegObj.imgfile != null && userRegObj.imgfile.FileName != null && userRegObj.imgfile.ContentLength > 1024000)//1 MB
                    {
                        TempData["msg"] = "danger~Profile Picture Should be Less Than 1 MB";
                        if (userRegObj.Id <= 0)
                        {
                            return View(userRegObj);
                        }
                        return RedirectToAction("Action", "Controller", new { id = userRegObj.Id });
                    }



                    else if (userRegObj != null && userRegObj.imgfile != null && userRegObj.imgfile.FileName != null)
                    {
                        string path = Path.Combine(Server.MapPath("~/Media/ProfilePics"), Path.GetFileName(userRegObj.imgfile.FileName)); // folder to save images
                        userRegObj.imagePath = Path.GetFileName(userRegObj.imgfile.FileName);
                        userRegObj.imgfile.SaveAs(path);
                    }

In view (This code will help you if your model having an image then it will show the image in the upload section else it will show a default image as you want to manage yourself) : 在视图中(如果您的模型有图像,则此代码将为您提供帮助,然后它将在上传部分中显示该图像,否则,您将根据自己的意愿显示一个默认图像):

@if (Model != null && Model.Id>0 &&Model.imagePath!=null)
                                        {
                                            <div class="form-group">
                                                <label for="exampleInputEmail1">Upload Your Image:<br /><small>(Width:155, Height:155)</small></label>
                                                <span class="imageupld">
                                                    <img src="@Url.Content("~/Media/ProfilePics/"+Model.imagePath)" alt="obsequium" id="profilepic"  style="margin-top:8.5px" />
                                                </span>
                                                <span class="file-up" style="overflow:hidden;">
                                                    <span class="pic" id="p">@Model.imagePath</span>
                                                    @Html.TextBoxFor(m => m.imgfile, new { @class = "profilepic", type = "file", data_value = "pic", tabindex = 17, accept = "image/*", id = "picVal", @onchange = "checkImage()" })
                                                    @Html.ValidationMessageFor(m => m.imgfile, "", new { @class = "text-red", id = "imgVal" })
                                                </span>
                                            </div>
                                        }
                                        else if (Model != null && Model.Id>0 && Model.imagePath == null )
                                        {
                                        <div class="form-group">
                                            <label for="exampleInputEmail1">Upload Your Image:<br /><small>(Width:155, Height:155)</small></label>
                                            <span class="imageupld">
                                                <img src="@Url.Content("~/Content/Template/")images/imgupload.png" alt="obsequium" id="profilepic" style="margin-top:8.5px">
                                            </span>
                                            <span class="file-up" style="overflow:hidden;">
                                                <span class="pic">Upload Image</span>
                                                @Html.TextBoxFor(m => m.imgfile, new { @class = "profilepic", type = "file", data_value = "pic", tabindex = 17, accept = "image/*", id = "picVal", @onchange = "checkImage()" })
                                                @Html.ValidationMessageFor(m => m.imgfile, "", new { @class = "text-red", id = "imgVal" })
                                            </span>
                                        </div>
                                    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM