2016-02-13 101 views

回答

2

您需要创建在DOM路径字符串来表示您浏览的文件,然后将其添加为背景图片网址。我通过修改你的代码来完成它的工作。

<body> 
    <form action="" id="contactproForm" method="post" ng-app="myApp" ng-controller="myCtrl" enctype="multipart/form-data"> 

     <label for="file">Attachment</label> 
     <div class="input-box"> 
      <input type="file" id="file" class="input-text" ngf-change="onChange(picFile)" ngf-select ng-model="picFile" name="attachement" accept="image/png, image/jpeg, image/jpg, application/msword, application/vnd.ms-excel, application/pdf " /> 
     </div> 
     <div id="image"class="image" style="width:200px;height:200px;background-image:url('');"></div>  <!-- div with id="image"--> 

    </form> 


    <script> 
    var app = angular.module('myApp', ['ngFileUpload']); 

    app.controller('myCtrl', ['$scope', '$http', '$timeout', '$compile', 'Upload', 
     function($scope, $http, $timeout, $compile, Upload) { 
      $scope.onChange = function(files) { 
       if (files[0] == undefined) return; 
       if($scope.isImage(files[0].name.split(".").pop())){ // checking if image 
        var path = URL.createObjectURL(files[0]);  // creating a path for file 
        document.getElementById('image').style.backgroundImage = "url(" + path + ")"; // setting it as background image of div 
       }else{ 
        alert("not Image"); 
       } 
      } 

      $scope.isImage = function(ext) { 
       if (ext) { 
        return ext == "jpg" || ext == "jpeg" || ext == "gif" || ext == "png" 
       } 
      } 
     } 
    ]); 
    </script> 

</body> 

我已添加对所作更改的评论。

+0

这可以通过将代码封装到自定义指令中进行改进 –

+0

另外,由于OP正在使用ng-file-upload,您可以使用ngf-background指令吗? https://github.com/danialfarid/ng-file-upload –

+0

有一个问题@nijeesh。 background-image不适用于pdf等。 –

0

使用ng样式代替这样的样式并替换i法师网址。

纳克风格=“{‘背景图片’:‘URL(https://www.google.com/images/srpr/logo4w.png)’}”>

+0

这对存储在用户本地机器上的图像不起作用。你需要打开这个文件,读取它的数据并像@Nijeesh的回答一样创建一个数据URL。 –