[英]Sending file in angular2
我需要通过POST在我的Web应用程序中发送文件。 我在Java中有一个服务器端,在Angle 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();
}
}
但是我收到一个错误: nested exception is org.springframework.web.multipart.MultipartException: The current request is not a multipart request
并且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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.