1

我想做的事

我继承了一个 Angular 项目,并且是该框架的新手。我正在尝试使用 Spire.Doc(免费版)打开启用宏的 word 文档并编辑文件,然后将编辑后的文件发送到客户端。我打电话给一个。Net Core 3 Web API 从一个角度组件通过一个报告服务。我需要向 API 发送一个 ID,打开并编辑 word 文件,然后将其发送回客户端。

我得到了什么

我尝试过的所有改变都得到了不同的结果。使用下面的代码,我可以下载一个 word 文档,但是一页文件现在是 54 页随机字符(编码错误?)。

我的代码

客户端.component.ts

public createForm() {
this.reportService.GetForm(this.clientId);
}

报告.service.ts

GetForm(clientId: string) {
    let params = new HttpParams()
        .set('clientId', clientId);
    this.http.get(environment.apiUrl + '/Reports/GenerateForm', { params: params, responseType: 'blob' })
        .subscribe(response => {
            let blob = new Blob([response], { type: 'application/msword' });
            const fileName = "Test Word Document.doc";
            saveAs(blob, fileName);
        });
}

报告控制器.cs

[HttpGet("GenerateReimbursementForm")]
public async Task<ActionResult<HttpResponseMessage>> GenerateForm(int clientId)
{
    var loggedInUser = this.GetLoggedInUser(this._context);
    if (!loggedInUser.HasSystemAccess)
        return Forbid();

    // get document
    string filename = "Test Word Document.doc";
    string path = Path.Combine(
        Directory.GetCurrentDirectory(), 
        "documents", 
        filename);

    Spire.Doc.Document doc = new Spire.Doc.Document(path);

    // do stuff to document
    Spire.Doc.Documents.Paragraph p = doc.CreateParagraph();
    p.Text = "testing...";

    //get stream from document in memory
    MemoryStream ms = new MemoryStream();
    doc.SaveToFile(ms, Spire.Doc.FileFormat.Doc);
    ms.Position = 0;

    // send to browser in http response message
    var result = new HttpResponseMessage(HttpStatusCode.OK);
    result.Content = new StreamContent(ms);
    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
    result.Content.Headers.ContentDisposition.FileName = filename;
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
    result.Content.Headers.ContentLength = ms.Length;

    return result;
}

我尝试过的事情

  • 不同的word文档 -相同的结果
  • 不同的单词类型(docx,docm) -单词表示它是损坏的文件
  • 使用不同的type值(都具有相同的结果):
    • 斑点
    • 应用程序/vnd.openxmlformats-officedocument.wordprocessingml.document
    • 数组缓冲区
  • 添加charset:utf-8;type字符串
  • 删除 Spire.Doc 代码 -结果相同
  • 从控制器返回 abyte[]而不是HttpResponseMessage使用memoryStream.ToArray()-相同的结果
  • 在组件代码而不是服务中创建并保存 blob -结果相同
  • 使链接按钮重定向到控制器路径并跳过 .ts 文件 -由于路径问题,无法使用此方法

任何帮助表示赞赏!

编辑

通过 Postman 发出 GET 请求时,我收到以下信息:

{"version":{"major":"1","minor":"1","build":"-1","revision":"-1","majorRevision":-1,"minorRevision":-1},"content":{"headers":[{"Key":"Content-Disposition","Value":["attachment; filename=\"Test Word Document.doc\""]},{"Key":"Content-Type","Value":["application/octet-stream"]},{"Key":"Content-Length","Value":["16384"]}]},"statusCode":200,"reasonPhrase":"OK","headers":[],"trailingHeaders":[],"requestMessage":null,"isSuccessStatusCode":true}
4

0 回答 0