gpt4 book ai didi

java - 在 angular2 中发送文件

转载 作者:行者123 更新时间:2023-12-01 09:09:43 25 4
gpt4 key购买 nike

我需要在我的网络应用程序中通过 POST 发送文件。我有一个java服务器端和一个Angular 2客户端。我需要客户端将文件发送到服务器。服务器代码:

@RequestMapping(method = RequestMethod.POST, value = "/run/file")
@ResponseBody
private void runImportRecordsJob(@RequestParam("file") MultipartFile file){
// Some code
}

客户代码:

组件:

export class ImportRecordsJobComponent implements OnInit {

file: File;


constructor(private jobsService: JobsService) { }


chooseFile(event: any){
this.file = event.srcElement.files[0];

console.log(this.file);
}

selectFormat(event: any){
if (event.length > 0)
this.format = event[0].key;
else
this.format = null;

}

runImportRecordsJob(){
if (confirm("Are you sure you want to run this job?")){
this.jobsService.runImportRecordsJob({file: this.file});
}
}

ngOnInit() {
}

}

服务:

@Injectable()
export class JobsService {

constructor(private http: Http) { }

runImportRecordsJob(importRecords: any){
var headers = new Headers({"Content-Type": 'application/json; multipart/form-data;'});
let options = new RequestOptions({ headers: headers });

let formData = new FormData();
formData.append("file", importRecords.file, importRecords.file.name);

this.http.post(SERVER + "/batches/run/file", formData, options).subscribe();
}

}

但我收到错误:嵌套异常是 org.springframework.web.multipart.MultipartException:当前请求不是多部分请求

formData 始终为空。谁能建议我一种在不使用 ng2-uploader 之类的情况下发送文件的方法。谢谢。

最佳答案

您是否错过了“CommonsMultipartResolver”bean?

<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 20 * 1024 * 1024 Byte = 20 MB-->
<property name="maxUploadSize" value="20971520" />
<property name="defaultEncoding" value="UTF-8" />
</bean>

编辑:

更改了服务的方法:

  runImportRecordsJob(importRecords: any){
let options = new RequestOptions();

let formData = new FormData();
formData.append("file", importRecords.file, importRecords.file.name);

console.log(formData);
console.log(importRecords);
this.http.post(SERVER + "/batches/run/file", formData, options).subscribe();
}

关于java - 在 angular2 中发送文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40995840/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com