typescript Agular2 + 打字稿 + 文件上传
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45490051/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Agular2 + typescript + file upload
提问by parikshitcs0072
I am creating an angular2 project, in which my requirement is to upload a file and send some parameters from client to server(Spring Rest Server). I have tried Formdata Interface, but when i am appending a file(File Object created from event.srcElement.files) to it and then logging the object to console it prints an empty formdata object. As for the server side i am using @requestparam("file") to fetch the file. It would be great if anyone can provide some help on this.
我正在创建一个 angular2 项目,其中我的要求是上传文件并将一些参数从客户端发送到服务器(Spring Rest Server)。我尝试过 Formdata 接口,但是当我将一个文件(从 event.srcElement.files 创建的文件对象)附加到它然后将对象记录到控制台时,它会打印一个空的 formdata 对象。至于服务器端,我使用 @requestparam("file") 来获取文件。如果有人可以为此提供一些帮助,那就太好了。
this is the code in my html file
这是我的 html 文件中的代码
<input type="file" #uploadFile multiple="true" (change)="uploadFile($event)"/>
component file is like this
组件文件是这样的
uploadFile(event:any){
let file = event.target.files[0];
let fileName = file.name;
console.log(file)
console.log(fileName)
let formData = new FormData();
formData.append('file',file);
this.examService.uploadAnswer(formData);
}
and in service file
并在服务文件中
uploadAnswer(formData:FormData){
console.log(formData)
this.http.post(this.url+'/uploadanswer', formData)
.map((response: Response) => {
let res = response.json();
Object.keys(res).forEach(name =>
this.questions=res[name]
);
});
采纳答案by Malik Shahzad
Your HTML should be:
你的 HTML 应该是:
<input id="file-field" name="file-field" (change)="uploadFile($event)" type="file" accept=".png,.jpg,.jpeg">
So you will get file in component as:
因此,您将在组件中获取文件为:
uploadFile(event) {
let files = event.target.files;
if (files.length > 0) {
console.log(file); // You will see the file
this.service.uploadFile(file);
}
}
And in service:
并在服务中:
uploadFile(file) {
let formData: FormData = new FormData();
formData.append('file', file, file.name);
this.http.post(url, formData, request_options)
}
Then you will get file in with file key in request data.
然后您将使用请求数据中的文件键获取文件。