【问题标题】:How to download or fetch a file from Project directory using jQuery如何使用 jQuery 从项目目录下载或获取文件
【发布时间】:2019-09-30 22:04:55
【问题描述】:

当用户单击调用 Jquery Ajax 函数的行时,我使用 JQuery 手动创建了一个 html 表。此函数调用 ASP.NET MVC 控制器,控制器调用在内部从文件服务器获取文件并存储到文件夹“..\download\”下的项目目录中。 我需要在浏览器中返回这个文件 JQuery 和可下载的文件。

调用 API 并将文件(任何类型)存储在项目目录中:

var response = _httpClient.GetAsync(documentURL).Result;
HttpContent content = response.Content;
string currfile = System.Web.Hosting.HostingEnvironment.MapPath(string.Format("~/download/"));
System.IO.DirectoryInfo di = new DirectoryInfo(currfile);
foreach (FileInfo file in di.GetFiles())
{
    file.Delete();
}
using (var file = new FileStream(System.Web.Hosting.HostingEnvironment.MapPath(string.Format("~/download/{0}.{1}", fileName, fileExt)), FileMode.CreateNew))
{ // create a new file to write to
    Stream contentStream = content.ReadAsStreamAsync().Result; // get the actual content stream                
    contentStream.CopyToAsync(file); // copy that stream to the file stream
    file.FlushAsync(); // flush back to disk before disposing
}

JQuery 调用

$("#DivAttachmentDetails  tr:not(:first)").click(function () {
    var DocumentumId = $(this).find("td:eq(0)").find(':input[name=hdnDocumentumId]').val();//$('#hdnDocumentumId').val();        
         $.ajax({
              type: 'POST',
              url: getExactPath('/Supplier/GetDocument'),
              data: {
                  documetObj: DocumentumId
              },
              dataType: 'json',
              async: false,
                  success: function (jsonData) {                              
              },
              error: function () {
                  alert("Unable to fetch the Document.");
              }
             });
             });

如何使用 JQuery 将此文件立即返回到浏览器。

【问题讨论】:

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


    【解决方案1】:

    将文件添加到“..\download\filename.pdf”后,我将发送回连接的文件夹名 + 文件名。我存储在解决方案目录文件夹中,因为页面使用量少于 5 个用户。

    string returnurl:
    using (var file = new FileStream(System.Web.Hosting.HostingEnvironment.MapPath(string.Format("~/download/{0}.{1}", fileName, fileExt)), FileMode.CreateNew))
    { // create a new file to write to
        Stream contentStream = content.ReadAsStreamAsync().Result; // get the actual content stream                
        contentStream.CopyToAsync(file); // copy that stream to the file stream
        file.FlushAsync(); // flush back to disk before disposing
    
        returnurl =  "\download\"+ fileName+"."+fileExt
    }
    

    JQuery:

    success: function (jsonData) 
    {                              
        window.open(jsonData.returnurl) // this opens the file in new windows as "http:\\projectname:8080\download\yourfilename.pdf" ( any file type)
    },
    

    【讨论】:

      猜你喜欢
      • 2017-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-18
      • 1970-01-01
      相关资源
      最近更新 更多