问题描述
我正在创建一个angular2项目,其中我的要求是上传文件并将一些参数从客户端发送到服务器(Spring Rest Server)。
我已经尝试了Formdata接口,但是当我追加一个文件(从Event.srcElement.files创建的文件对象)到它,然后记录对象到控制台打印一个空的formdata对象。
至于服务器端我使用@requestparam(文件)来获取文件。
如果有人可以提供一些帮助,这将是非常好的。
这是我的HTML文件中的代码
< input type =file#uploadFile multiple =true(change)=uploadFile($ event)/>
组件文件就像这样
uploadFile(event:any){
let file = event.target.files [0];
让fileName = file.name;
console.log(file)
console.log(fileName)
let formData = new FormData();
formData.append('file',file);
this.examService.uploadAnswer(formData);
$ / code>
和服务档案
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]
);
});
您的HTML应该是:
< input id =file-fieldname =file-field(change)=uploadFile($ event)type =file accept =。png,.jpg,.jpeg>
所以你会得到文件在组件:
uploadFile(event){
let files = event.target.files;
if(files.length> 0){
console.log(file); //你会看到文件
this.service.uploadFile(file);
$ / code $ / pre
在服务中:
uploadFile(file){
let formData:FormData = new FormData();
formData.append('file',file,file.name);
$ b $ this.http.post(url,formData,request_options)
}
然后,您将获得请求数据中的文件密钥文件。
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.
this is the code in my html file
<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]
);
});
解决方案 Your HTML should be:
<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.
这篇关于Agular2 +打字稿+文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!