【问题标题】:Adding image to AngularJS model for upload将图像添加到 AngularJS 模型以进行上传
【发布时间】:2014-09-12 02:14:31
【问题描述】:

我是这个美妙的框架 AngularJS 的新手。我有一个 C# API 控制器,我想从包含图像的表单上传数据。通常(剃刀)我会将表单上传为 json 并将图像包含为 HttpPostedFileBase:

public ArtWork SaveArtWork(ArtWork artWork, HttpPostedFileBase file)
    { // save in db and return object }

我发现了很多不同的方式来上传包裹在 FormData 对象中的文件 ([AngularJS Uploading An Image With ng-upload):

$scope.uploadFile = function(files) {
var fd = new FormData();
//Take the first selected file
fd.append("file", files[0]);

$http.post(uploadUrl, fd, {
    withCredentials: true,
    headers: {'Content-Type': undefined },
    transformRequest: angular.identity
}).success( ...all right!... ).error( ..damn!... );
};

但我还有一些其他属性已解析为 json 对象,现在我想将它们全部上传到一个包中。或者是否可以将图像数据作为 base64 并将其添加到我的 json 对象中?我知道 base64 比字节流大 1/3,但它很容易使用:)

这是我的 Angular 控制器:

'use strict';

(函数(){

// Factory
angular.module('umbraco').factory('artworkResource', function ($http) {
    return {
        getById: function (id) {
            return $http.get("backoffice/Trapholt/ArtWorkApi/GetById/" + id);
        },
        save: function (artwork) {
            return $http.post("backoffice/Trapholt/ArtWorkApi/SaveArtWork", angular.toJson(artwork));
        },
        save2: function (artwork, fd) {
        return $http.post("backoffice/Trapholt/ArtWorkApi/SaveArtWork", angular.toJson(artwork), fd);
    }
    };
});

// Controller
function artworkController($scope, $routeParams, artworkResource, $http) {

    $scope.categories = ['Keramik', 'Maleri', 'Møbel', 'Skulptur'];

    artworkResource.getById($routeParams.id).then(function (response) {
        $scope.curatorSubject = response.data;
    });


    var fd;
    $scope.uploadFile = function(files) {
        fd = new FormData();
        fd.append("file", files[0]);
    };

    $scope.save = function (artwork) {
        artworkResource.save(artwork, fd).then(function (response) {
            $scope.artwork = response.data;

            alert("Success", artwork.Title + " er gemt");
        });
    };


};
//register the controller
angular.module("umbraco").controller('ArtworkTree.EditController', artworkController);

})();

那么如何将我的图像和其他属性组合在一个 json 对象或两个参数中?如果我需要更多解释,请发表评论,任何帮助将不胜感激:)

【问题讨论】:

    标签: c# angularjs


    【解决方案1】:

    我找到了一个解决方案,将文件和模型添加到表单数据中。所以实际上很容易从here 扩展解决方案。这是我的 Angular 控制器:

    function artworkController($scope, $routeParams, artworkResource, $http) {
    
        $scope.categories = ['Keramik', 'Maleri', 'Møbel', 'Skulptur'];
    
        artworkResource.getById($routeParams.id).then(function (response) {
            $scope.curatorSubject = response.data;
        });
    
    
        var fd;
        $scope.uploadFile = function(files) {
            fd = new FormData();
            fd.append("file", files[0]);
        };
    
        $scope.save = function (artwork) {
    
            fd.append("ArtWork", angular.toJson(artwork));
    
            $http.post("backoffice/Trapholt/ArtWorkApi/Post", fd, {
                transformRequest: angular.identity,
                headers: { 'Content-Type': undefined }
            });
        };
    
    
    };
    

    这是我的 C# mvc API 控制器:

    public HttpResponseMessage Post()
        {
            HttpResponseMessage result = null;
            var httpRequest = HttpContext.Current.Request;
            if (httpRequest.Files.Count > 0)
            {
                var file = httpRequest.Files[0];
                var artworkjson = httpRequest.Form[0];
                var artwork = JsonConvert.DeserializeObject<ArtWork>(artworkjson);
                if (artwork == null)
                {
                    return Request.CreateResponse(HttpStatusCode.BadRequest, "No saved");
                }
    
                using (var binaryReader = new BinaryReader(file.InputStream))
                {
                    artwork.Picture = binaryReader.ReadBytes(file.ContentLength);
                }
    
                result = Request.CreateResponse(HttpStatusCode.Created, "ok");
            }
            else
            {
                result = Request.CreateResponse(HttpStatusCode.BadRequest);
            }
            return result;
        }
    

    html 视图是一个普通表单,所有输入都与模型绑定,除了文件输入字段:

    <input type="file" id="file" name="picture" onchange="angular.element(this).scope().uploadFile(this.files)"/>
    

    【讨论】:

      猜你喜欢
      • 2022-01-11
      • 1970-01-01
      • 2017-04-27
      • 2019-03-15
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多