如何在angularjs中将变量的值设置为上传文件的json数据? [英] How to set a variable's value to uploaded file json data in angularjs?

查看:35
本文介绍了如何在angularjs中将变量的值设置为上传文件的json数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是angularJS的新手.我想使用上传JSON文件< input type ="file" onchange ="angular.element(this).scope().uploadFile(this.files)"/>

I'm new to angularJS. I want to upload a JSON file using <input type="file"onchange="angular.element(this).scope().uploadFile(this.files)"/>

我正在尝试像这样在控制器中访问其数据:

and I am trying to access its data in the controller like this:

$scope.uploadFile = function(files) {

$scope.jsonData = files[0].data;

};

但是我的变量中有未定义的内容.我必须使用此变量来填充网站上的其他各个字段.请帮助我如何访问上传的输入文件的数据.

But I get an undefined in my variable. I have to use this variable to populate various other fields on the website. Kindly help me how to access the data of the input file uploaded.

推荐答案

您需要使用

FileReader对象使Web应用程序可以异步读取用户计算机上存储的文件(或原始数据缓冲区)的内容.

The FileReader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer.

其方法 FileReader.readAsText()

readAsText 方法用于读取指定的Blob或File的内容.

The readAsText method is used to read the contents of the specified Blob or File.

注意:这是一个示例,它适用于现代浏览器

Note: Here is an example, It works in Modern browsers

$(document).ready(function() {
  $('#file').change(function(e) {
    var reader = new FileReader();
    reader.onload = function(e) {
      console.log(e.target.result);
      
      //if you want in JSON use      
      //var json = JSON.parse(e.target.result)
    }
    reader.readAsText(this.files[0]);
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="file" name="file" />

这篇关于如何在angularjs中将变量的值设置为上传文件的json数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆