如何使用AngularJS获取在文件资源管理器中选择的文件的URL

时间:2018-08-08 07:43:59

标签: angularjs angularjs-directive angularjs-scope

我需要单击选择文件并从文件资源管理器中选择文件,然后我需要获取所选文件的URL并将其存储在变量中。请查看下面的代码并为我提供指导我是AnularJS的新手,谢谢。

public class SimpleScannerActivity extends Activity implements ZBarScannerView.ResultHandler {

    private ZBarScannerView mScannerView;

    @Override
    public void onCreate(Bundle state) {
        super.onCreate(state);
        mScannerView = new ZBarScannerView(this);    // Programmatically initialize the scanner view
        setContentView(mScannerView);                // Set the scanner view as the content view
    }

    @Override
    public void onResume() {
        super.onResume();
        mScannerView.setResultHandler(this); // Register ourselves as a handler for scan results.
        mScannerView.startCamera();          // Start camera on resume
    }

    @Override
    public void onPause() {
        super.onPause();
        mScannerView.stopCamera();           // Stop camera on pause
    }

    @Override
    public void handleResult(Result rawResult) {
        // Do something with the result here
        Log.v(TAG, rawResult.getContents()); // Prints scan results
        Log.v(TAG, rawResult.getBarcodeFormat().getName()); // Prints the scan format (qrcode, pdf417 etc.)

        // If you would like to resume scanning, call this method below:
        mScannerView.resumeCameraPreview(this);
    }
}

1 个答案:

答案 0 :(得分:0)

您可以创建url directive。在控制器内部,您应使用$watch方法来捕捉要分配file_name属性的时刻。在此示例中,您可以选择图片文件,它将显示:

angular.module('app', [])
  .controller('ctrl', ['$scope', function($scope) {
    $scope.$watch('file_url', function(newVal, oldVal) {
      if (newVal != oldVal)
        console.log(newVal);
    }, true)
  }])
  .directive('url', function() {
    return {
      restrict: 'A',
      scope: {
        url: '='
      },
      link: function(scope, element) {
        element.on('change', function(event) {
          var reader = new FileReader();
          reader.onloadend = function() {
            scope.$apply(function() {
              scope.url = reader.result;
            });
          }

          var file = element[0].files[0];
          if (file)
            reader.readAsDataURL(file);
        })
      }
    }
  })
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>

<div ng-app='app' ng-controller="ctrl">
  <img src="{{file_url}}" height="150" alt="Image preview...">
  <input type="file" url='file_url'>
</div>