[英]File download link in ASP.NET MVC application
在我的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?
您可以使用jQuery.ajax而不是HTTP GET来实现AJAX调用,并在检查目标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) 我可以检查URL是否存在文件吗?
(2) 如何使用c#MVC4在$ .ajax中调用错误函数?
CMIIW。
是。 默认情况下,浏览器捕获http状态并呈现适当的页面。 但是,如果要修改此行为并显示JavaScript警报,则需要在JavaScript(Ajax)中实现它。
更新:
这里有一些关于如何使用Ajax下载文件的重要资源。
和
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.