我正在写url重定向。现在我正在努力解决这个问题:
假设我有这样一个方法:
public FileResult ImageRedirect(string url)
,我传递这个字符串作为输入:http://someurl.com/somedirectory/someimage.someExtension
.
现在,我希望我的方法从someurl
下载该图像,并将其作为File()
返回。我该怎么做呢?
使用WebClient
类从远程url下载文件,然后使用Controller.File
方法返回。WebClient类中的DownLoadData
方法将为您完成此任务。
所以你可以写一个这样的动作方法,它接受fileName(url到文件)
public ActionResult GetImage(string fileName)
{
if (!String.IsNullOrEmpty(fileName))
{
using (WebClient wc = new WebClient())
{
var byteArr= wc.DownloadData(fileName);
return File(byteArr, "image/png");
}
}
return Content("No file name provided");
}
可以通过调用
来执行yoursitename/yourController/GetImage?fileName="http://somesite.com/logo.png
因为可能允许用户让你的服务器下载网络上的任何文件,我认为你应该限制下载文件的最大大小。
可以使用下面的代码:
public static MemoryStream downloadFile(string url, Int64 fileMaxKbSize = 1024)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
webRequest.Credentials = CredentialCache.DefaultCredentials;
webRequest.KeepAlive = true;
webRequest.Method = "GET";
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
Int64 fileSize = webResponse.ContentLength;
if (fileSize < fileMaxKbSize * 1024)
{
// Download the file
Stream receiveStream = webResponse.GetResponseStream();
MemoryStream m = new MemoryStream();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = receiveStream.Read(buffer, 0, buffer.Length)) != 0 && bytesRead <= fileMaxKbSize * 1024)
{
m.Write(buffer, 0, bytesRead);
}
// Or using statement instead
m.Position = 0;
webResponse.Close();
return m;
}
return null;
}
catch (Exception ex)
{
// proper handling
}
return null;
}
在你的情况下,像这样使用:
public ActionResult GetImage(string fileName)
{
if (!String.IsNullOrEmpty(fileName))
{
return File(downloadFile(fileName, 2048), "image/png");
}
return Content("No file name provided");
}
fileMaxKbSize表示允许的最大大小(kb)(默认为1Mb)