Track file download hits/count in ASP.NET MVC5

时间:2018-02-03 07:51:56

标签: c# asp.net razor

I have to download file from server directory and keep its download count on Database. However, I got this to work by the following code.

Razor View

<a href="@Url.Action("Download", "Home", new {id = item.Id})">Download</a>

Controller

    private AppDbContext db = new AppDbContext();

    public ActionResult Download(int id)
    {
        Item item = db.Items.Find(id);

        if (item != null)
        {
            item.DownloadCount++;
            db.SaveChanges();

            return File(item.Location, MimeMapping.GetMimeMapping(item.Location), Path.GetFileName(item.Location));
        }

        return HttpNotFound();
    }

This code works perfectly fine except the downloads can't be resumed later. I know there is other way to download a file using HTML tag like below (which is resumable)...

<a href="/myfile.mp4" download>Download</a>

But, how do I count download on this way?

1 个答案:

答案 0 :(得分:1)

After hours of browsing I found a solution that works...

Razor View

<a onclick="download(@item.Id)">Download</a>

Javascript

function download(id) {
        $.ajax({
            url: '@Url.Action("Download", "Home", new {id = "id"})'.replace('id', id),
            type: "GET",
            success: function (result) {
                if (result.success) {
                    var link = document.createElement('a');
                    link.href = result.fileLocation;
                    link.download = '';
                    link.click();

                } else {
                    alert(result.responseText);
                }
            },
            error: function (errormessage) {
                alert(errormessage.responseText);
            }
        });
    }

Controller

public ActionResult Download(int id)
        {
            Item item = db.Items.Find(id);

            if (item != null)
            {
                item.DownloadCount++;
                db.SaveChanges();

                string fileLocation = string.Format(
                    "{0}/{1}",
                    Request.Url.GetLeftPart(UriPartial.Authority),
                    item.Location.Replace(@":\\", "/").Replace(@"\", "/")
                );

                return Json(new { success = true, fileLocation = fileLocation},
                    JsonRequestBehavior.AllowGet);
            }

            return Json(new { success = false, responseText = "Bad request." },
                JsonRequestBehavior.AllowGet);
        }