【问题标题】:File download link in ASP.NET MVC applicationASP.NET MVC 应用程序中的文件下载链接
【发布时间】:2016-06-16 08:21:15
【问题描述】:

在我的 MVC 应用程序中,当用户单击特定链接(a href)时,将下载图像。

下面是下载图片的动作代码

public ActionResult Download()
    {
        try
        {
            HttpClient client = new HttpClient();
            byte[] data = client.GetByteArrayAsync("http://public.slidesharecdn.com/b/images/logo/linkdsfsfsfsfedin-ss/SS_Logo_White_Large.png?6d1f7a78a6").Result;
            return File(data, "application/jpg", "testimage.jpg");
        }
        catch (Exception err)
        {
            return new HttpNotFoundResult();
        }
    }

但如果出现异常,它将显示默认的 IIS“HTTP 错误 404.0 - 未找到”页面, 相反,我想显示 javascript 警报“找不到图像”。

要实现这个要求,我是否需要进行 AJAX 调用,而不是 直接 HTTP GET?

【问题讨论】:

  • 是的,如果你想在图片选择页面上显示

标签: c# asp.net-mvc


【解决方案1】:

您可以使用 jQuery.ajax 实现 AJAX 调用而不是 HTTP GET,并在检查目标 URL 中是否存在文件后发送正确的响应:

<script type="text/javascript">
$.ajax({
    cache: false,
    url: "@Url.Action("Download", "Controller")",
    data: { imageUrl: [your image link here], fileName: [image filename] },
    dataType: 'json',
    success: function (data) {
       // download image to client's browser
    },
    error: function (err) {
       alert(err);
    }
});
</script>

// note that input variable should match with AJAX call data parameter
public ActionResult Download(String imageUrl, String fileName) 
{
    // check if image URL exists by reading response header
    boolean fileExist;
    HttpWebResponse response = null;
    var request = (HttpWebRequest)WebRequest.Create(imageUrl);
    request.Timeout = 10000; // in milliseconds, e.g. 10 sec
    request.Method = "HEAD";

    try
    {
        response = (HttpWebResponse)request.GetResponse(); // get validity response
        fileExist = response.StatusCode == HttpStatusCode.OK;

        if (fileExist)
        {
            HttpClient client = new HttpClient();
            byte[] data = client.GetByteArrayAsync(imageUrl);
            return File(data, "application/jpg", fileName);
        }
        else
        {
            return new HttpStatusCodeResult(404, "Image not found");
        }
    }
    catch (Exception err)
    {
         return new HttpStatusCodeResult(400, "Bad request" + err.Message); // 404 also eligible here, assume it is bad request
    }
    finally
    {
        if (response != null) 
        {
            response.Close();
        }
    }
}

参考:

(1)can I check if a file exists at a URL?

(2)How to call error function in $.ajax with c# MVC4?

CMIIW。

【讨论】:

    【解决方案2】:

    是的。默认情况下,浏览器会捕获 http 状态并呈现适当的页面。但是,如果您想修改此行为并显示 JavaScript 警报,则需要在 JavaScript (Ajax) 中实现它。

    更新:

    这里有一些关于如何使用 Ajax 下载文件的好资源。

    Download a file by jQuery.Ajax

    download file using an ajax request

    【讨论】:

    • 但是图像没有被下载,但是如果出现 404 错误,会显示警报。
    • 不。您将根据状态以不同的方式处理相同的请求。如果成功,则连接下载逻辑,否则显示警报。
    • 添加你的评论(你提到链接的那个)作为你的答案,我会接受它作为答案,你说呢?
    • 这是另一个值得一看的链接。 stackoverflow.com/questions/4545311/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多