从MVC控制器获取FileStream到Client

时间:2015-07-09 23:17:22

标签: c# asp.net asp.net-mvc asp.net-mvc-4

我使用下面的代码将文件流放入由MVC控制器返回的响应消息中。但是如何在客户端获取流?任何评论高度赞赏! 谢谢!

服务器:

string filename = @"c:\test.zip";

FileStream fs = new FileStream(filename, FileMode.Open);

HttpResponseMessage response = new HttpResponseMessage();

response.Content = new StreamContent(fs);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

return response;

2 个答案:

答案 0 :(得分:4)

如果您只是尝试下载二进制数据,则应该使用FileContentResult类型或FileStreamResult类型,可以Controller方式访问string filename = @"c:\test.zip"; var bytes = System.IO.File.ReadAllBytes(filename); return File(bytes, "application/octet-stream", "whatevernameyouneed.zip"); } class。

这是一个简单的例子:

var client = new HttpClient();
var response = await client.GetAsync("protocol://uri-for-your-MVC-project");

if(response.IsSuccessStatusCode)
{
    // Do *one* of the following:

    string content = await response.Content.ReadAsStringAsync();
    // do something with the string

    // ... or ...

    var bytes = await response.Content.ReadAsByteArrayAsync();
    // do something with byte array

    // ... or ...

    var stream = await response.Content.ReadAsStreamAsync();
    // do something with the stream

}

您可能想要添加代码以确保文件存在等。如果您很好奇,也可以在MSDN上阅读File方法。

在您的WebForms项目中,您可以非常轻松地从该控制器读取响应:

/*
 (*) mean All Elements , this code remove all margin and padding from all element include html and body also  ^_^
*/
*{
  margin:0;
  padding:0;
}

如果由您决定,您阅读回复的方式;因为你还没有真正描述客户网站应该对你正在阅读的文件做什么,所以很难更具体。

答案 1 :(得分:1)

如果您想要更强大的解决方案并更好地控制文件检索,请随时使用以下内容:

/// <summary>
/// Returns a file in bytes
/// </summary>
public static class FileHelper
{
    //Limited to 2^32 byte files (4.2 GB)
    public static byte[] GetBytesFromFile(string fullFilePath)
    {

        FileStream fs = null;

        try
        {
            fs = File.OpenRead(fullFilePath);
            var bytes = new byte[fs.Length];
            fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
            return bytes;
        }
        finally
        {
            if (fs != null)
            {
                fs.Close();
                fs.Dispose();
            }
        }

    }
}

控制器:

    public FileResult DownloadPdf()
    {
        var filePath = Server.MapPath("~/Content/resume/BrentonBates_WebDev_Resume.pdf");
        var pdfFileBytes = FileHelper.GetBytesFromFile(filePath);
        return File(pdfFileBytes, "application/pdf", "Brenton Bates Business Application Developer.pdf");
    }

还可以查看以下内容:http://www.mikesdotnetting.com/article/125/asp-net-mvc-uploading-and-downloading-files

希望它有所帮助...

也许您想要一个类似于以下内容的实现:

string fileName = "test.zip";
string path = "c:\\temp\\";
string fullPath = path + fileName;
FileInfo file = new FileInfo(fullPath);

Response.Clear();
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.ContentType = "application/x-zip-compressed";
Response.WriteFile(fullPath);
Response.End();