从MVC控制器到客户端获取FileStream

本文关键字:获取 FileStream 客户端 MVC 控制器 | 更新日期: 2023-09-27 18:01:52

我使用下面的代码将一个文件流放入由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;

从MVC控制器到客户端获取FileStream

如果您只是试图下载二进制数据,您应该使用FileContentResult类型或FileStreamResult类型,可以通过Controller类上的File方法访问。

下面是一个简单的例子:

string filename = @"c:'test.zip";
var bytes = System.IO.File.ReadAllBytes(filename);
return File(bytes, "application/octet-stream", "whatevernameyouneed.zip");

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

在你的WebForms项目中,你可以很容易地从这个控制器读取响应:

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
}

你阅读回复的方式取决于你;由于您没有真正描述客户端站点应该如何处理您正在阅读的文件,因此很难更具体。

如果您想要更强大的解决方案和对文件检索的更多控制,请随意使用以下命令:

/// <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();