您好我是angular2的新手,我正在尝试从angular2上传一个excel 前端。我想要实现的是,从angular2上传excel 前端将它传递给后端的Springboot,我会在springboot内部 必要的更改。最后将其传回角度以在屏幕上呈现。
My Approach :
let user select the excel from frontend
POST it to springboot backend , make necessary modification using apache POI
Finally pass it to angular again to render it on screen .
Problem Area :-
I have made the frontend part to recieve input
below is my code :-
<input type="file" id="myfile" class="form-control" [(ngModel)]="fileObj" (change)="upload($event)" accept=".xlsx">
Angular Component method to called on change of element :-
file: File
upload(event : EventTarget){
let eventObj : MSInputMethodContext = <MSInputMethodContext> event ;
let target : HTMLInputElement = <HTMLInputELement> eventObj.target ;
let files : FileList = target.files ;
this.file = files[0];
this._appService.sendFile(this.file);
}
above functions calls the sendFile method in appservice of angular2
below is the code for appService :-
private headers = new Headers({'Content-Type' : 'multipart/form-data'});
sendFile(fileObj : File){
return this.http.post('http://localhost:9000/submitexcel', fileObj, {headers : this.headers}).map(res => res.json().data).subscribe();
}
Springboot Controller接收传入的文件。
@RestController
public class ExcelUploadController {
@RequestMapping(method = RequestMethod.POST , value="/submitexcel")
public ResponseEntity<String> getFile(@RequestParam("File") MultipartFile file){
System.out.println("inside controller");
}
}
每当我调用控制器时,我都会在控制台上出错: -
“请求被拒绝,因为没有找到多部分边界”
以下是我的问题: -
2.我的方法是否正确以达到要求?
3.如何将excel从springboot发送回角度以显示在前端?
我尝试了很多关于此的搜索,但找不到任何有用的东西
请帮助我,我被困了好多天,谢谢
答案 0 :(得分:0)
试试这个 appService
sendFile(fileObj : File){
let headers = new Headers();
let options = new RequestOptions({ headers: headers });
let formData = new FormData();
formData.append('file', fileObj);
return this.http.post('http://localhost:9000/submitexcel', formData, options).map(res => res.json().data).subscribe();
}
Spring Controller
@RestController
public class ExcelUploadController {
@RequestMapping(method = RequestMethod.POST , value="/submitexcel")
public ResponseEntity<String> getFile(@RequestParam MultipartFile file){
System.out.println(file.getOriginalFilename());
}
}
答案 1 :(得分:0)
问题很可能是您明确指定Content-Type
,请尝试{'Content-Type' : undefined}
,这会让浏览器确定正确的Content-Type
我认为这种方法没有任何问题。至于您的客户端将如何接收修改后的excel,那么您要么必须使用excel来响应提交excel的相同请求,要么您必须让服务器在另一个回调上提供excel文件。