简体   繁体   English

我无法在asp.net Core 2.0剃须刀页面中执行下载操作

[英]I'm unable to perform download operation in asp.net core 2.0 razor pages

I'm working on Document Management System,but unable to perform Download operation through SQL database in asp.net core 2.0 razor pages,bellow are more details about my project. 我正在使用文档管理系统,但是无法在asp.net core 2.0剃须刀页面中通过SQL数据库执行下载操作,下面是有关我的项目的更多详细信息。

Index.cshtml Index.cshtml

@page
@model IndexModel
@{
    ViewData["Title"] = "Schedules";
}

<div style="background-color:aliceblue;">
    <hr />

    <div class="well well-sm " style="background-color:lightskyblue;height:50px;"><h3 style="text-align:center;color:white;font-weight:bold;margin-top:0px;"> +Add Files</h3></div>

    <div class="row">
        <div class="col-md-4">
            <form method="post" enctype="multipart/form-data">
                <div class="form-group">
                    <label asp-for="FileUpload.Title" class="control-label"></label>
                    <input asp-for="FileUpload.Title" type="text" class="form-control" />
                    <span asp-validation-for="FileUpload.Title" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <label asp-for="FileUpload.UploadPublicSchedule" class="control-label"></label>
                    <input asp-for="FileUpload.UploadPublicSchedule" type="file" class="form-control                        btn btn-primary btn-sm float-left" style="height:auto" />
                    <span asp-validation-for="FileUpload.UploadPublicSchedule" class="text-                     danger"></span>
                </div>
               <input type="submit" value="Upload" class="btn btn-primary" />
            </form>
        </div>
    </div>
    <hr />
    <h3>Loaded Schedules</h3>
    <table class="table " style="background-color:lightskyblue;">

        <thead style="font-weight:bold ;color:white;background-color:black;margin-right:-50px;padding-right:80px;">
            <tr style="background-color:darkblue;color:white;">


                <th>
                    @Html.DisplayNameFor(model => model.Schedule[0].Title)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Schedule[0].UploadDT)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Schedule[0].PublicScheduleSize)
                </th>
                @*<th class="text-center">
                        @Html.DisplayNameFor(model => model.Schedule[0].PrivateScheduleSize)
                    </th>*@
                <th class="text-center">Operations</th>
                <th></th>
            </tr>

        </thead>

        <tbody>
            @foreach (var item in Model.Schedule)
            {
                <tr style="font-weight:bold">
                    <td>
                        @Html.DisplayFor(modelItem => item.Title)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.UploadDT)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.PublicScheduleSize)
                    </td>

                    <td style="margin-left:-60px;">
                        @*<a asp-page="./Delete" asp-route-id="@item.ID">Delete</a>*@
                        <a asp-page="./Delete" asp-route-id="@item.ID" class="btn btn-danger glyphicon glyphicon-trash" role="button">Delete</a>

                    </td>
                    <td>
                        <a asp-page-handler="karuna.txt" role="button"
                           download>
                            download the license
                        </a>
                    </td>
                   </tr>
            }
        </tbody>
    </table>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
<script>
    function createPDFLink(fileName) {
        var doc = new pdf();
        // whatever content you want to download
        var a = document.createElement("a");
        a.download = fileName;
        a.title = "download as PDF";
        a.href = doc.output('datauri', { "fileName": name });
        return a;
    }

    // some paragraph in the page
    document.querySelector(
        "p.saveaspdf"
    ).appendChild(createPDFLink(
        "document-" + document.title + ".pdf"
    ));
</script>

This is the Page Model: 这是页面模型:

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using DMS.Models;
using DMS.Utilites;
using System.IO;
using System.Runtime.InteropServices.ComTypes;

namespace DMS.Pages.Schedules
{
    public class IndexModel : PageModel
    {
        private readonly DMS.Models.DatabaseContext _context;

        public IndexModel(DMS.Models.DatabaseContext context)
        {
            _context = context;
        }

        [BindProperty]
        public FileUpload FileUpload { get; set; }

        public IList<Schedule> Schedule { get; private set; }

        public async Task OnGetAsync()
        {
            Schedule = await _context.Schedule.AsNoTracking().ToListAsync();
        }

        public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                Schedule = await _context.Schedule.AsNoTracking().ToListAsync();
                return Page();
            }

            var publicScheduleData =
                await FileHelpers.ProcessFormFile(FileUpload.UploadPublicSchedule, ModelState);

            if (!ModelState.IsValid)
            {
                Schedule = await _context.Schedule.AsNoTracking().ToListAsync();
                return Page();
            }

            var schedule = new Schedule()
            {
                PublicSchedule = publicScheduleData,
                PublicScheduleSize = FileUpload.UploadPublicSchedule.Length,
                Title = FileUpload.Title,
                UploadDT = DateTime.UtcNow
            };

            _context.Schedule.Add(schedule);
            await _context.SaveChangesAsync();

            return RedirectToPage("./Index");
        }
    }
}
  • I'm trying to download all the files from database . 我正在尝试从数据库下载所有文件。
  • All Pages are connected to the database . 所有页面均已连接到数据库。

I'm not sure exactly what you are trying to do. 我不确定您要做什么。 You page has a mix of file upload and download stuff. 您的页面混合了文件上传和下载内容。

For file downloads I do the following. 对于文件下载,请执行以下操作。 On the .cshtml page I have a button with that will call a Post handler on the code behind page. 在.cshtml页面上,我有一个按钮,它将在页面后面的代码上调用Post处理程序。 Like: 喜欢:

<button id='@("download"+item.ID)' asp-page-handler="DownloadFile" 
  asp-route-externalId="@item.ExternalId" 
  class="btn btn-primary">Download Report
</button>

Then in the code behind I have a handler that in my loads the report from the db gets a zip file of all of the files and then returns that to the browser which triggers the download. 然后,在后面的代码中,我有一个处理程序,该处理程序在加载数据库时从报告中获取所有文件的zip文件,然后将其返回到触发下载的浏览器。 The important part is returning the PhysicalFile from the handler with the path to the file on disk. 重要的部分是从处理程序返回PhysicalFile以及磁盘上文件的路径。

    /// <summary>
    /// Return the zip file for the requested id.
    /// </summary>
    /// <param name="externalId">Report external id</param>
    public async Task<IActionResult> OnPostDownloadFileAsync(string externalId) {

        var report = LoadReport();
        if (report == null) {
            return Page();
        }

        var zipFile = report.GetReportDownload();
        string filename = FileUtils.WebSafeFileName(zipFile, ".zip");
        return PhysicalFile(zipFile, "application/zip", filename);
    }

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

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