Md. Sahidul Islam
Md. Sahidul Islam

Reputation: 351

How can I upload file by form submit in angular2?

How can I upload file by form submit in angular2. I want to use ng2-file-upload library. But I'm not able to use it in form submit. Can anyone help me please?

Upvotes: 1

Views: 3225

Answers (2)

Akkusativobjekt
Akkusativobjekt

Reputation: 2023

So finally I understand your problem, which appears do be additional formdata you want to send with the file. After you created your FileUploader, you can add additional form with the following code :

uploader: FileUploader = new FileUploader({ url: "http://localhost/upload.php" });

  constructor() {
  this.uploader.onBuildItemForm = (item, form) => {
      form.append("key1", "value1");
      form.append("key1", "value2");
    };
}

Some say it's a little bit prettier to put this code in the ngOnInit(), but I don't want to bloat this code and this decision is not very important here.

Afterwards you can inspect the additional post data in the payload of the http post, for example with the Firefox Developer Tools. They should look like:

-----------------------------110224700718602891206418821
Content-Disposition: form-data; name="key1"

value1
-----------------------------110224700718602891206418821
Content-Disposition: form-data; name="key1"

value2

(Your boundary wont be the same)

I found the solution on the GitHub tracker of the project.

Upvotes: 0

Jorawar Singh
Jorawar Singh

Reputation: 7621

It should be possible by just passing the uploaded file in your method which can be called in submit.

In your HTML

<form #sieFileUploadForm="ngForm">
  <input type="file" id="fileItem" 
  value="Browse...">

In you ts

uploadFile(file){
 console.log(file)
}

Note:- when sending to beckend you need to make it formdata like this

uploadFile(file){
 let formData = new FormData();
 formData.append('FILENAME', file);
}

Upvotes: 2

Related Questions