我需要在一个请求中发布一个PDF文件和一个FormGroup。我尝试以FormData和FormGroup的形式传递PDF,并将两者都添加到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
});
}发布于 2021-03-08 13:22:08
看上去你的角度很好。我做了一件类似的事情,需要将文件作为“文件”传递,以便让我的后端(C#和南希一起)作为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));
}https://stackoverflow.com/questions/66530309
复制相似问题