ASP.NET MVC应用程序中的文件下载链接

时间:2016-06-16 08:21:16

标签: c# asp.net-mvc

在我的MVC应用程序中,当用户点击特定链接(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 alert" Image not found"。

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

2 个答案:

答案 0 :(得分: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。

答案 1 :(得分:0)

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

更新

以下是有关如何使用Ajax下载文件的一些很好的资源。

Download a file by jQuery.Ajax

download file using an ajax request