Angular 2-下载CSV文件 [英] Angular 2 - download csv file

查看:177
本文介绍了Angular 2-下载CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Microsoft Web API 2控制器下载csv文件.这是我到目前为止的内容:-

I'm trying to download a csv file from a Microsoft Web API 2 controller. Here's what I have so far:-

Web API:-

    [Route("extractContent/{extractId}")]
    public async Task<IHttpActionResult> GetExtractContent(int extractId)
    {
        _logger.Info($"Getting extract file content for extract with id: {extractId}...");

        try
        {
            IEnumerable<ExtractDto> extracts = await _extractService.GetExtractsAsync(new ExtractSearchRequest { ExtractId = extractId });

            ExtractDto extract = extracts?.FirstOrDefault();

            if (extract != null)
            {
                string path = extract.FilePath;

                HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);

                var stream = new FileStream(path, FileMode.Open, FileAccess.Read);

                using (result.Content = new StreamContent(stream))
                {
                    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                    {
                        FileName = Path.GetFileName(path)
                    };
                    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

                    return Ok(result);
                }
            }
            throw new InvalidOperationException($"Could not find extract with id: {extractId}");
        }
        catch (Exception e)
        {
            _logger.ErrorException($"An error occured trying to get extract content for extract with id: {extractId}", e);

            return InternalServerError(e);
        }
    }

Angular 2下载服务:-

Angular 2 Download Service:-

@Injectable()
export class DownloadService {
private baseAddress: string;
private headers: Headers;
private options: RequestOptions;

constructor(private http: Http, private config: Config, private errorService: ErrorService) {
    this.baseAddress = config.cache.get('portfolioUploadApiUrl');
    this.headers = new Headers({ 'Content-Type': 'application/json' });
    this.options = new RequestOptions({ headers: this.headers, withCredentials: true, responseType:  ResponseContentType.Blob});
}

getExtractContent(extractId: number): Observable<Blob> {

    return this.http.get(this.baseAddress + 'extractContent/' + extractId, this.options)
        .map((response: Response) => 
            {
                return new Blob([response.blob()], {type: 'application/csv'});
            }
        )
        .catch(this.errorService.handleError);
}

}

Angular 2客户代码:-

Angular 2 client code:-

onDownload(): void {
    if (this.extract && this.extract.FilePath) {
        this.downloadService.getExtractContent(this.extractId).subscribe(blob => {
            var date = new Date();
            var day = date.getDay();
            var month = date.getMonth();
            var year = date.getFullYear();
            var seconds = date.getSeconds();
            var minutes = date.getMinutes();
            var hours = date.getHours();
            var formattedDate = day + '' + (month + 1) + '' + year + '' + hours + '' + minutes + '' + seconds;
            var fileName = "Extract" + this.extractId + "-" + formattedDate + ".csv";
            FileSaver.saveAs(blob, fileName)
        })
    }
}

但是,当我运行下载时,我下载了一个包含以下内容的csv文件:-

However, when I run the download, I get a csv file downloaded which has the following in it:-

{版本":{"_ Major":1 _次要:1 _Build:-1 _Revision:-1}内容:{"Headers":[{"Key":"Content-Disposition"值:[附件; filename = \"RPModel_Portfolio_ISY-20170925.csv \"]} {" Key:" Content-Type值:[" application/octet-stream]}]} StatusCode:200 ReasonPhrase:"OK"标头:[] RequestMessage:null IsSuccessStatusCode:true}

{"Version":{"_Major":1 _Minor:1 _Build:-1 _Revision:-1} Content:{"Headers":[{"Key":"Content-Disposition" Value:["attachment; filename=\"RPModel_Portfolio_ISY - 20170925.csv\""]} {"Key":"Content-Type" Value:["application/octet-stream"]}]} StatusCode:200 ReasonPhrase:"OK" Headers:[] RequestMessage:null IsSuccessStatusCode:true}

任何人都可以帮忙吗?

谢谢

推荐答案

我不知道如何解决这个问题,所以我只从Web API操作中提供了csv数据的json表示,然后仅使用了Angular2Csv Angular 2库可将此json对象转换为CSV文件

I couldn't figure out how to get around this so I went with just providing a json representation of my csv data from my Web API action and then just using Angular2Csv Angular 2 library to convert this json object into a CSV file

由于某种原因,使用ResponseMessage(result)而不是其他Web API包装器之一(例如Ok(result))意味着对于实际请求,CORS被忽略. OPTIONS(飞行前)请求似乎可以正常工作,但使用ResponseMessage(result)时GET无效,但是使用Ok(result)时GET有效,因此我只能假定Ok(result)正在使用Cors功能Web API 2中提供的

For some reason, using ResponseMessage(result) rather than one of the other Web API wrappers (such as Ok(result)) means that CORS gets ignored for the actual request. The OPTIONS (pre-flight) request seems to work but the GET doesn't when using ResponseMessage(result) but it does when using Ok(result) so I can only assume that Ok(result) is doing something to use the Cors functionality provided in Web API 2

这篇关于Angular 2-下载CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆