无法从上传的文件中获取正确的文件格式

时间:2017-12-14 06:51:35

标签: javascript jquery angularjs

这是我的代码。当我上传文档后点击save分割文件格式。

  • 当我上传图片时,我会收到data:image/jpeg
  • 当我上传pdf时,我会收到data:application/pdf

当我上传.txt个文件时,我遇到了一个问题data:text/plain

为什么我得不到data:text/txt

类似于docs/docx/xls,它会像data:application/vnd.openxmlformats-officedocument.wordprocessingml.document

一样返回

var app = angular.module('myApp', [])
app.controller('myController', function($scope) {
   
    $scope.saveDetails = function(doc) { 
         console.log(doc.file)   
            doc.type = doc.file.split(';')[0]
        console.log(doc.type)
    };
})
app.directive("fileread", [function () {
    return {
        scope: {
            fileread: "="
        },
        link: function (scope, element, attributes) {
            element.bind("change", function (changeEvent) {
                var reader = new FileReader();
                reader.onload = function (loadEvent) {
                    scope.$apply(function () {
                        scope.fileread = loadEvent.target.result;
                    });
                }
                reader.readAsDataURL(changeEvent.target.files[0]);
            });
        }
    }
}]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myController" ng-init="init()">
    <input type="file" id="file1" name="file"  fileread="doc.file"/>
    <button ng-click="saveDetails(doc)">save</button>
</div>

这里的问题是什么?为什么我没有获得txt/docs/docx/xls的正确扩展名?

1 个答案:

答案 0 :(得分:0)

split

再次输入:类型

如果我们的data如下:

var data = "data:type;test"

//first split the `;`
var ext = data.split(";")[0];

//next split `:` from ext to get the type
var type = ext.split(":")[1];