1

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?

2
  • What do you mean with "I'm not able", errors? Did you look up the demo ( valor-software.com/ng2-file-upload ) ? Commented Dec 12, 2016 at 15:08
  • 1
    I want to click form submit button and want to submit all data with image/file to backend. How can I do this? @Akkusativobjekt Commented Dec 14, 2016 at 14:09

2 Answers 2

2

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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Actually you just need a input field with the ng2FileSelect directive and a binding to the uploader, eg [uploader]="uploader". An additional button which calls the ulpoad() method and you are done. There is no need to create a FormData object, AFAIK.
I want to submit others field's data by clicking form submit button.
Yes u should be able to do that as i mentioned, just pass the data to the method!
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.