0

I select the file in template like this:

 <input type="file" #fileupload [(ngModel)]="myFile" name="myFile" (change)="fileChange(fileupload.files)" />

then in component use this function to manipulate the object:

fileChange(event){
console.log( event);
this.myFile = event[0];}

Compilation is OK and no errors, but I get this error in browser:

ERROR Error: [object Object]
at viewWrappedDebugError (core.es5.js:8410)
at callWithDebugContext (core.es5.js:13475)
at Object.debugHandleEvent [as handleEvent] (core.es5.js:13053)
at dispatchEvent (core.es5.js:8602)
at core.es5.js:9213
at HTMLInputElement.<anonymous> (platform-browser.es5.js:2651)
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:424)
at Object.onInvokeTask (core.es5.js:3881)
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
at Zone.webpackJsonp.../../../../zone.js/dist/zone.js.Zone.runTask (zone.js:191)

And

ERROR Error: Uncaught (in promise): InvalidStateError: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string.
Error: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string.

In fact I can see the object contains my selected file, but still get error.

enter image description here

Al007
  • 383
  • 1
  • 5
  • 15

1 Answers1

1

You cannot change the value of a file upload input with javascript for security reasons. Without a plunkr or anything it's hard to say, but I think your error is happening here: this.myFile = event[0]; A quick check you be to set a temporary variable instead of this.myFile.

Edit: You need to remove ngModel, and change the argument of fileChange to be just "event" and not fileupload.files. Then this should work.

dockleryxk
  • 407
  • 2
  • 11
  • What you mean by "change the value of a file upload input"? I am just try to use the value. Could you please explain more? – Al007 Aug 24 '17 at 12:37
  • Check my edit, but for security reason explanation check here: https://stackoverflow.com/questions/1696877/how-to-set-a-value-to-a-file-input-in-html – dockleryxk Aug 24 '17 at 14:00