ASP MVC通过从sftp读取将文件返回到浏览器

时间:2016-06-10 07:04:38

标签: asp.net asp.net-mvc-4 filestream memorystream ssh.net

我能够从sftp获取文件流但无法在控制器的浏览器(chrome)中呈现它。

如果我将文件存储在磁盘中然后返回其工作正常但我想通过直接返回流而不是存储任何文件

来做到这一点

以下是我的代码

public ActionResult View(字符串路径)         {

        string contentType = "";

        var filePath = Server.MapPath(path);

        switch (System.IO.Path.GetExtension(filePath).ToLower())
        {
            case ".htm":
            case ".html":
                contentType = "text/HTML";
                break;

            case ".txt":
                contentType = "text/plain";
                break;

            case ".doc":
            case ".rtf":
            case ".docx":
                contentType = "Application/msword";
                break;

            case ".xls":
            case ".xlsx":
                contentType = "Application/x-msexcel";
                break;

            case ".jpg":
            case ".jpeg":
                contentType = "image/jpeg";
                break;

            case ".gif":
                contentType = "image/GIF";
                break;

            case ".png":
                contentType = "image/png";
                break;

            //case ".bmp":
            //    contentType = "image/x-ms-bmp";
            //    break;

            case ".pdf":
                contentType = "application/pdf";
                break;
            case ".bmp":
                contentType = "image/bmp";
                break;
        }

        try
        {

            Stream file = null;

            SftpClient conn = null;


            if (contentType != "")
            {
                conn = GetSFTPConnection();

                conn.Connect();

                file = new MemoryStream();

                if (conn.Exists(path))
                {
                    conn.DownloadFile(path, file);
                }
                else
                {
                    throw new SftpPathNotFoundException();
                }

                return File(file, contentType);

            }
        }
        catch (Exception)
        {

            throw new Exception("Unable To Get Requested File");
        }
        return null;
    }

1 个答案:

答案 0 :(得分:-1)

我没有对此进行过测试,但我认为您需要将文件发送到响应中,例如替换:

return File(file, contentType);

使用:

var response = HttpContext.Current.Response;
response.BufferOutput = false;
response.OutputStream.Write(file, 0, file.Length);
response.Flush();
response.End();

并且可能会更改您的操作以返回FileResult而不是ActionResult。