簡體   English   中英

ASP.NET MVC - 如何返回FileResult,而文件是在另一個站點?

[英]ASP.NET MVC - how to return a FileResult, while file is at another site?

我正在寫url重定向器。 現在我正在努力解決這個問題:

假設我有這種方法:

public FileResult ImageRedirect(string url)

我將此字符串作為輸入傳遞: http://someurl.com/somedirectory/someimage.someExtensionhttp://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

因為您可能允許用戶讓您的服務器下載Web上的任何文件,所以我認為您希望限制最大下載文件大小。

為此,您可以使用以下代碼:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM