如何更改图像的名称?

时间:2018-04-25 09:16:43

标签: javascript angularjs html5 image-processing angularjs-directive

Angularjs

app.directive('fileModel', ['$parse', function ($parse) {
return {
    restrict: 'A',
    link: function(scope, element, attrs) {
        var model = $parse(attrs.fileModel);
        var modelSetter = model.assign;

        element.bind('change', function(){
            scope.$apply(function(){
                modelSetter(scope, element[0].files[0]);
            });
        });
    }
};
}]);

app.service('fileUpload', ['$http', function ($http) {
this.uploadFileAndFieldsToUrl = function(file, fields, uploadUrl){
    var fd = new FormData();
    fd.append('file', file);
    console.log(file) //File { name: "franklindroosevelt1.jpg", lastModified: 1522139208000, lastModifiedDate: Date 2018-03-27T08:26:48.000Z, webkitRelativePath: "", size: 63159, type: "image/jpeg" }
    for(var i = 0; i < fields.length; i++){
        fd.append(fields[i].name, fields[i].data)

    }
    console.log(file)//File { name: "franklindroosevelt1.jpg", lastModified: 1522139208000, lastModifiedDate: Date 2018-03-27T08:26:48.000Z, webkitRelativePath: "", size: 63159, type: "image/jpeg" }
    $http.post(Appname+"/upload_image/", fd, {
        transformRequest: angular.identity,
        headers: {'Content-Type': undefined}
    })
    .success(function(){
    })
    .error(function(){
    });
}
}]);


app.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){

$scope.$watch('myFile', function(newFileObj){
    if(newFileObj)
        $scope.filename = newFileObj.name;
});

$scope.uploadForm = function(){
    var file = $scope.myFile;
    var uploadUrl = "/formUpload";
    var fields = [{"name": "filename", "data": $scope.filename}];
    fileUpload.uploadFileAndFieldsToUrl(file, fields, uploadUrl);
};

}]);

HTML

 <div class="maincontent">
     <div ng-app="Appschedule" ng-controller="myCtrl" class="container container1">
        <p>
            <input type="file" file-model="myFile"/>
        </p>
        <p>
            <label>File Name:</label>
            <input type="text" ng-model="filename"></input>
        </p>
        <button ng-click="uploadForm()">upload me</button>
    </div>

</div>

我编写了一个代码将图像上传到目录,这里我想根据输入文本或任意随机名称更改图像名称。我无法更改名称,上传时名称保持不变。有没有其他方式来发送名称。请帮帮我

1 个答案:

答案 0 :(得分:1)

  

还有其他方式发送名称吗?

以下是显示如何在同一请求中将名称作为字符串和文件发送的代码:

req.body.data

在服务器端,它位于upload(req, res, function (err) { if (err) { res.json({error_code: 1, err_desc: err}); return; } console.log(req.body.data); res.json({error_code: 0, err_desc: null}); }) ,因此可以收到,如下所示:

{{1}}