Recently, I am using Angular2 and need to have a function to upload files, but I don’t want to use the library, so I directly use the native input file tag.
<input type="file" >
Then I wanted to get the uploaded content, so I first thought of a stupid method, first obtain the input tag through id, and then get the uploaded content in it
const uploadsFile = (name).files[0];
The result was an error。 Then look at the prompt that HTMLElement has no files method. So I found the type with the files attribute in es6, which is the HTMLInputElement type. So it is forced to convert to this type。
const uploadsFile=<HTMLInputElement>(name).files[0];
The result is still not good, and finally it is changed to convert the type first and then call the attribute.
const uploadsFile = <HTMLInputElement>(name); const file = [0];
Later I found that this method seemed a bit stupid, so I changed the method and used $event in angular2 to get the input content, which also included the file to be uploaded.
<input type="file" (change)="getUpload(newUpload, $event)" >
The selected file is in
private getUpload(obj, e) { if ([0]) { const file = [0]; = file; } }
Then you can put it in formdata
const formData = new FormData(); ('file', );
Finally, clear the selected uploaded content to use
let upload = <HTMLInputElement>(selectorName); = null;
I don’t know if there is a better way, so I welcome discussion and correction.
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.