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

时间:2017-08-06 22:02:13

标签: c# asp.net asp.net-mvc file asp.net-mvc-5

我是ASP.Net MVC 5的初学者,我想知道如何在数据库中上传文件并将其显示给用户。我在互联网上看到了与上述问题相关的众多例子。但所有关于将文件放入某个解决方案文件夹的讨论但我想将文件上传到数据库,并能够在"详细信息视图"中找回它。

问题:我可以在数据库中上传文件,但我不知道如何显示用户的文件链接。单击哪个用户应该能够查看/下载上载的文件。以下是我的尝试。

型号:

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

控制器:

// 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);
}

查看: Details.chtml 文件

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

所以,在数据库中,我可以在&#34; Content&#34;中找到一些二进制内容条目。柱。但我不知道如何在详细信息部分显示一些链接。我想在详细信息视图中显示文件链接。单击将下载文件或预览等内容。请指导我。

编辑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;
}

2 个答案:

答案 0 :(得分:0)

假设您的控制器中的代码正确填充了您的模型,您只需<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <style> #plates, #foods { cursor:pointer; } .selected { font-weight:700; } </style> <div id="result">Please select a plate and a food</div> <table cellspacing="0px" cellpadding="20px"> <thead> <th>Plates</th> <th>Foods</th> </thead> <tbody> <tr> <td id="plates"> <div id='p1'>Plate 1</div> <div id='p2'>Plate 2</div> <div id='p3'>Plate 3</div> <div id='p4'>Plate 4</div> <div id='p5'>Plate 5</div> <div id='p6'>Plate 6</div> </td> <td id="foods"> <div id='f1'>Food 1</div> <div id='f2'>Food 2</div> <div id='f3'>Food 3</div> <div id='f4'>Food 4</div> </td> </tr> </tbody> </table>对图像进行编码并显示该图像。

base64

同样看看这个问题:OWASP java Encode.forHtml(rawUserInput)

答案 1 :(得分:0)

在模型中添加以下代码:

            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; }

在控制器中(这将验证您的图片的效果超过您的操作1mb,如果您想在发布之前验证它,可以将其谷歌搜索以进行jquery验证):

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);
                    }

在视图中(此代码将帮助您,如果您的模型有图像,那么它将在上传部分显示图像,否则它将显示您想要自己管理的默认图像):

@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>
                                    }