【问题标题】:ASP MVC return file to browser by reading from sftpASP MVC 通过从 sftp 读取将文件返回给浏览器
【发布时间】:2016-06-10 07:04:38
【问题描述】:

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

如果我将文件存储在磁盘中,然后返回它的工作正常,但我想通过直接返回流而不是存储任何文件来做到这一点

下面是我的代码

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;
    }

【问题讨论】:

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


    【解决方案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。

    【讨论】:

    • 工作正常。谢谢
    • 谢谢,你能接受这个作为答案吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-11
    • 1970-01-01
    • 1970-01-01
    • 2015-04-02
    • 2016-09-28
    相关资源
    最近更新 更多