【问题标题】:Web API and angularjs to download Excel fileWeb API 和 angularjs 下载 Excel 文件
【发布时间】:2015-07-30 03:26:05
【问题描述】:

我已通过 Web API 成功地将 Excel 电子表格上传到我的文件服务器。现在我需要能够下载相同的文件并允许用户修改它。使用我当前的代码,结果只是垃圾。

这是我的服务器代码 -

factory.downloadFile = function(id) {
    return $http.get(serviceBase1 + 'downloadFile/' + id).then(function (datafile) {
        return datafile.data;
    });
}

这是我在 API 中的控制器代码,是从另一篇文章中借来的 -

[Route("downloadFile/{id}")]
[HttpGet]
public HttpResponseMessage DowloadFile(string id)
{
    var fileInfo = FileInformationRepository.GetFileInfoById(id);

    var localFilePath = HttpContext.Current.Server.MapPath("~/UploadedDocuments/" + fileInfo.FileName);

    if (!File.Exists(localFilePath))
    {
        return Request.CreateResponse(HttpStatusCode.NotFound);
    }
    else
    {
        HttpResponseMessage result = Request.CreateResponse(HttpStatusCode.OK);
        result.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
        result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
        result.Content.Headers.ContentDisposition.FileName = fileInfo.FileName;
        return result;
    }
}

LocalFilePath 正确 - C:\Development\OpticalSystems\OpticalSystems.WebApi\UploadedDocuments\Quotation Sheet (s).xls 返回数据的标题是 - application/json, text/plain, /。而且返回的数据是——ࡱ,当然是我打不开的东西。我知道我即将完成这项工作。

【问题讨论】:

    标签: angularjs rest asp.net-web-api


    【解决方案1】:

    我能够通过对我的控制器进行这些更改来使其工作 -

    [Route("downloadFile/{id}")]
    [HttpGet]
    public HttpResponseMessage DowloadFile(string id)
    {
        var fileName = FileInformationRepository.GetFileInfoById(id).FileName;
        string filePath = string.Concat(GetDownloadPath(), "\\", fileName);
    
        HttpResponseMessage result;
        if (!File.Exists(filePath))
        {
            result = Request.CreateResponse(HttpStatusCode.Gone);
        }
        else
        {// serve the file to the client
            result = Request.CreateResponse(HttpStatusCode.OK);
            result.Content = new StreamContent(new FileStream(filePath, FileMode.Open, FileAccess.Read));
            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
            result.Content.Headers.ContentDisposition.FileName = fileName;
        }
    
        return result;
    }
    
    public static string GetDownloadPath()
    {
        return HttpContext.Current.Server.MapPath("~/UploadedDocuments");
    }
    

    【讨论】:

      猜你喜欢
      • 2021-02-13
      • 1970-01-01
      • 1970-01-01
      • 2017-01-24
      • 2018-02-01
      • 2015-09-17
      • 1970-01-01
      • 2014-09-10
      • 2014-07-27
      相关资源
      最近更新 更多