简体   繁体   English

如何读取angular中上传文件的内容?

[英]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.我目前正在研究 angular 项目,其中用户通过将文件拖放到指定区域来上传文件。 Then, I want to send the file content to the backend to store it in mongo.然后,我想将文件内容发送到后端以将其存储在 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.我曾尝试使用 FileReader() 读取文件的内容,但我无法让它工作。 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().我希望能够将内容存储到变量中,而不仅仅是执行 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.您应该将文件作为表单数据附加到 requestbody 中并发送。 If you still want to read it, there are libraries available to convert that file to json object.如果您仍想阅读它,可以使用库将该文件转换为 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(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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