简体   繁体   中英

How to read the content of an uploaded file in angular?

I am currently working on an angular project in which the user uploads a file by dropping it into a designated area. Then, I want to send the file content to the backend to store it in mongo. Unfortunately, what it gets send is the name of the file, but the content does not. I haver tried to read the content of the file using FileReader() but I was not able to get it to work. Any ideas of what would be the best/easiest way to read the content of the file?

I would like to be able to store the content into a variable rather than just doing console.log(). I think it will make it easier for the post but all suggestions are welcome. Thank you!

Note: to make this shorter I have only added this bit of code where I think the logic would be done but I can add more things if it helps.

    @HostListener('drop', ['$event']) public ondrop(evt) {
    evt.preventDefault();
    evt.stopPropagation();
    this.background = '#f5fcff'
    this.opacity = '1'
    let files = evt.dataTransfer.files;

    // I tried to read the file content here trying to do reader.readAsText(files); but it did not work

    if (files.length > 0) {
      this.onFileDropped.emit(files)
    }

  }

You should not read content of file. You should be appending the file as a formdata in requestbody and send it. If you still want to read it, there are libraries available to convert that file to json object. For directly sending file refer code below:-

const formData = new FormData();  
formData.append('file', file.data);  
this.httpClient.post<any>(this.SERVER_URL, formData).subscribe(); 

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