MVC从远程服务器下载文件

时间:2016-06-27 14:09:19

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

我正在尝试从远程服务器下载文件但我遇到了错误。

public ActionResult Download()
{
    var a = new Uri("file://<<REMOTE_SERVER>>/<<Folder>>/Test.csv");
    return File(a, "application/csv", "test.csv");
}

错误:

file://<<REMOTE_SERVER>>/<<Folder>>/Test.csv is not a valid virtual path.

3 个答案:

答案 0 :(得分:1)

using System.Security.Principal;          

using (new Impersonator("myUsername", "myDomainname", "myPassword"))
          {
             return File(@"<<REMOTE_SERVER>>\<<Folder>>\Test.csv", "application/csv", "test.csv");
          }

如果添加@符号,它将禁用任何转义字符。除此之外,你只有一个/在你的路径中间,这就是它无效的原因。

点击此处了解更多信息:https://msdn.microsoft.com/en-us/library/w070t6ka(v=vs.110).aspx

答案 1 :(得分:0)

尝试使用直接路径:

var a = "\\\<<REMOTE_SERVER>>\\<<Folder>>\\Test.csv";
return File(a, "application/csv", "test.csv");

答案 2 :(得分:0)

[HttpGet]
public EmptyResult DownloadAttachment()        
{
    var filePath = "http://img.local.com/Images/Customers/15364053/Inv_LMEM1LA6543_1.png";

    using (WebClient client = new WebClient())
    {
        byte[] imageData = client.DownloadData(filePath);

        string contentType = "";
        if (fileName.ToLower().Contains(".png"))
        {
            contentType = "Images/png";
        }
        else if (fileName.ToLower().Contains(".jpg"))
        {
            contentType = "Images/jpg";
        }
        else if (fileName.ToLower().Contains(".jpeg"))
        {
            contentType = "Images/jpeg";
        }
        else if (fileName.ToLower().Contains(".pdf"))
        {
            contentType = "Images/pdf";
        }
        else if (fileName.ToLower().Contains(".tiff"))
        {
            contentType = "Images/tiff";
        }

        Response.ContentType = contentType;
        Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
        Response.ContentType = "image/JPEG";
        Response.OutputStream.Write(imageData, 0, imageData.Length);
        Response.End();

    }
    return new EmptyResult();
}