如何在单个请求中发布pdf和formgroup?

pb3s4cty  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(296)

我需要发布一个pdf文件和一个在一个请求formgroup。我尝试将pdf作为formdata和formgroup原样传递,并将两者添加到formdata中。我不知道如何同时传递这两个,或者需要在rest请求中添加什么注解。
在我的ts中:

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控制器中:

@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);
}

编辑:找到解决方案:

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
        });
       }
at0kjp5o

at0kjp5o1#

看起来你的Angular 很好。我做了类似的操作,需要将文件作为“file[0]”传递,以便让我的后端(c#with nancy)将文件作为 Files 收藏。

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代码可以帮助你;

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

相关问题