如何仅在asp.net核心中上载.pdf文件并将名称和文件URL保存在表中,并使用户能够下载文件 [英] How to upload a .pdf file only in asp.net core and save the name and fileurl in table and enable users to download the file

查看:56
本文介绍了如何仅在asp.net核心中上载.pdf文件并将名称和文件URL保存在表中,并使用户能够下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在asp.net核心中上载pdf文件并将文件属性(文件名,dateuploaded,fileUrl)保存在表中,用户还应该能够在索引页面视图中下载文件.

How to Upload a pdf file in asp.net core and save the file attributes (filename, dateuploaded, fileUrl) in table, also a user should be able to download the file in the index page view.

该文件未上传到wwwwroot/images文件夹中,并且未在表中保存文件路径.

The file does not upload in wwwwroot/images folder and does not save filepath in the table.

控制器

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("DeliveryUploadId,DeliveryNo,FileName,Files,createdAt")] DeliveryUpload deliveryUpload, IFormFile Files)
{
    if (ModelState.IsValid)
    {
        using (var ms = new MemoryStream())
        {
            Files.CopyTo(ms);
            deliveryUpload.Files = ms.ToArray();
        }

        _context.Add(deliveryUpload.Files);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }
    return View(deliveryUpload.Files);
}

创建视图

<div class="row">
    <div class="col-md-4">
        <form asp-action="Create" method="post" enctype="multipart/form-data">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="DeliveryNo" class="control-label"></label>
                <input asp-for="DeliveryNo" class="form-control" />
                <span asp-validation-for="DeliveryNo" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="FileName" class="control-label"></label>
                <input asp-for="FileName" class="form-control" />
                <span asp-validation-for="FileName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Files" class="control-label"></label>
                <input type="file" id="files" asp-for="Files" />
                <span asp-validation-for="Files" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

索引视图

<th>
    @Html.DisplayNameFor(model => model.Files)
</th>
<td>
    <img class="img-responsive full-width" src="data:image/jpeg;base64,@Convert.ToBase64String(item.Files)" />
</td>

上传文件将文件路径/URL保存在表中.允许用户在索引页面中下载文件

Upload the file Save filepath/url in table. Enable users to download the file in the index page

推荐答案

您可以使用 IFormFile 接收文件.然后使用EF core将文件路径URL保存到数据库中.记住要创建一个 myFiles 文件夹,该文件夹首先将上传的文件保存在 wwwroot 下.

You could use IFormFile to receive the file.And then save the file path url to your database using EF core. Remember to create a myFiles folder where to save uploaded files under wwwroot firstly.

您可以参考下面是一个简单的演示:

Below is a simple demo:

型号:

public class Engineer
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string FilePath { get; set; }
}
public class EngineerVM
{
    public string Name { get; set; }
    public IFormFile File{ get; set; }
}

查看:

@model EngineerVM
<form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="Index">
<div class="form-group">
    <div class="col-md-10">
        <input type="text" asp-for="Name" />
    </div>
    <div class="col-md-10">
        <p>Upload one or more files using this form:</p>
        <input type="file" name="file"/>
    </div>
</div>
<div class="form-group">
    <div class="col-md-10">
        <input type="submit" value="Save" />
    </div>
</div>
</form>

控制器:

public class HomeController : Controller
{
    private readonly IHostingEnvironment _hostingEnv;
    private readonly ApplicationDbContext _context;

    public HomeController(IHostingEnvironment hostingEnv,ApplicationDbContext context)
    {
        _hostingEnv = hostingEnv;
        _context = context;
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Index(EngineerVM engineerVM)
    {
        if (engineerVM.File != null)
        {
            //upload files to wwwroot
            var fileName = Path.GetFileName(engineerVM.File.FileName);
            //judge if it is pdf file
            string ext =Path.GetExtension(engineerVM.File.FileName);
            if(ext.ToLower() != ".pdf")
            {
                return View();
            }
            var filePath = Path.Combine(_hostingEnv.WebRootPath, "images", fileName);

            using (var fileSteam = new FileStream(filePath, FileMode.Create))
            {
                await engineerVM.File.CopyToAsync(fileSteam);
            }
            //your logic to save filePath to database, for example

            Engineer engineer = new Engineer();
            engineer.Name = engineerVM.Name;
            engineer.FilePath = filePath;

            _context.Engineers.Add(engineer);
            await _context.SaveChangesAsync();
        }
        else
        {

        }
        return View();
    }
}

如果要下载文件,可以使用以下代码:

If you would like to download the file you could use below code:

索引视图:

@model IEnumerable<Engineer>

<td>
    <a asp-action="DownloadFile" asp-route-filePath="@item.FilePath">Download</a>                 
</td>

动作:

 public IActionResult DownloadFile(string filePath)
    {

        byte[] fileBytes = System.IO.File.ReadAllBytes(filePath);
        string fileName = "myfile.pdf";
        return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);

       //For preview pdf and the download it use below code
       // var stream = new FileStream(filePath, FileMode.Open);
       //return new FileStreamResult(stream, "application/pdf");
    }

这篇关于如何仅在asp.net核心中上载.pdf文件并将名称和文件URL保存在表中,并使用户能够下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆