首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在一个请求中发布PDF和FormGroup?

如何在一个请求中发布PDF和FormGroup?
EN

Stack Overflow用户
提问于 2021-03-08 12:59:39
回答 1查看 46关注 0票数 0

我需要在一个请求中发布一个PDF文件和一个FormGroup。我尝试以FormData和FormGroup的形式传递PDF,并将两者都添加到FormData中。我不知道如何同时传递两者,也不知道我需要在REST请求中添加什么注释。

在我的ts中:

代码语言:javascript
复制
 onSubmit() {
    const formData = new FormData();
    formData.append('pdfFile', this.myfile);

    this.form.removeControl('pdfFile');
    formData.append('invoice', this.form.value)

    this.http.post("http://localhost:8080/zugferd/matform", formData)
      .subscribe(res => {
        console.log(res);
      });
  }

在我的Spring控制器中:

代码语言:javascript
复制
@CrossOrigin(origins = "http://localhost:4200")
@PostMapping(value = "/matform")
public void both(@RequestPart("pdfFile") MultipartFile pdfFile, @RequestPart("invoice") MyInvoice invoice ,HttpServletResponse response) throws IOException {
    System.out.println(invoice.getSender().getStreet());
    System.out.println(pdfFile);
}

编辑:找到解决方案:

代码语言:javascript
复制
      onSubmit() {
        const formData = new FormData();
        formData.append('pdfFile', this.myfile);
        this.form.removeControl('pdfFile');
        
        const json = JSON.stringify(this.form.value);
        const blob = new Blob([json], {type: 'application/json'})
        formData.append('form', blob)
        this.http.post("http://localhost:8080/zugferd/matform", formData)
          .subscribe(res => { 
            //stuff
        });
       }
EN

回答 1

Stack Overflow用户

发布于 2021-03-08 13:22:08

看上去你的角度很好。我做了一件类似的事情,需要将文件作为“文件”传递,以便让我的后端(C#和南希一起)作为Files集合的一个元素来获取文件。

代码语言:javascript
复制
const formData = new FormData();
formData.append('file[0]', this.file, this.file.name);
formData.append('editObject', JSON.stringify(this.editObject));

const uri = "/v1/someUri";
this.httpService.post(uri, formData, 'json', true)
    .subscribe(() => this.onDataSaved(), err => this.onError("Could not save file.", err));

在服务中,我认为您需要获得整个请求,并根据边界分离条目(至少我找不到任何其他方法)。我不熟悉Spring,但也许这个C#代码可以帮助您在路上;

代码语言:javascript
复制
var contentType = new ContentType(Request.Headers.ContentType);
var boundary = $"--{contentType.Boundary}";

using (var reader = new StreamReader(Request.Body))
{
    var body = reader.ReadToEnd();
    var startTag = "Content-Disposition: form-data; name=\"editObject\"";
    var jsonPart = StringHelper.ValueBetween(body, startTag, boundary);

    var editObject = JsonConvert.DeserializeObject<SomeEditObject>(jsonPart);

    return await ExecuteCommandAsync(commandProcessorAsync, new AddFileCommand(editObject, Request.Files));
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66530309

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档