简体   繁体   中英

Angular 2 - upload of file

I need to create upload of images to my webserver in my Angular 2 app. Can anybody provide me some guidance how to achive this?

These are the prerequisities:

  • ASMX web service communicating in JSON.
  • post method used for communication.
  • JPEG / PNG up to 1MB of size.

Concept I wanted to follow (but failed)

Load the content of JPEG to variable, encode it using the Base64 coding and post it to ASMX service that will accept two parameters (token for authentication and encoded data.

What exactly is my problem

Web service was the easy part, it is done and working, but I can't manage to get the file content for enconding. I used this:

component.html

...
<input type="file" (change)="fileChangeEvent($event)" />
...

component.ts

private fileChangeEvent(fileInput: any) {
    let image = fileInput.target.files[0] as File;
    ...
}

As you have probably guessed, the problem is in the File class, because it provides me only basic info about the file (name, size, last modif, ...) but I can't get the content of the file. Or at least I don't know how to get it. I also checked other questions here on SO, but all of the answers had something special that did not met my requirements. And maybe I'm just blind, but I can't see where the content is get.

So, is there anybody, who is able to provide me some guidelines to follow?

Thank you very much in advance.

I have left this question open for experienced guys, who could be able to answer it. There is no answer though and I found out the answer yesterday. So, after some research and modification of search phrase, I found out the answer. There is a FileReader type which can be used for reading the content of the file. Here is the source of the answer:

Getting byte array through input type = file

Thanks to original answer now I know how to do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM