Web API和angularjs下载Excel文件

时间:2015-07-22 18:37:55

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

我已成功通过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, / 。返回的数据是 - ࡱ ,这当然是我无法打开的。我知道我接近完成这项工作。

1 个答案:

答案 0 :(得分:0)

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

[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");
}