向AngularJS模型中添加图片以便上传

本文关键字:AngularJS 模型 添加 | 更新日期: 2023-09-27 18:13:59

我刚接触这个很棒的框架AngularJS。我有一个c# API控制器,我想从一个包含图像的表单上传数据。通常(剃刀)我会上传一个json格式的表单,并包括图像作为httppostdfilebase:

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

我发现了很多不同的方式来上传文件包装在一个FormData对象([AngularJS上传一个图像与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对象,现在我想把它全部上传到一个bundle中。或者有可能获得图像数据作为base64并将其添加到我的json对象?我知道base64比字节流大1/3,但它很容易使用:)

这是我的Angular控制器:

'use strict';

(function () {

)
// 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对象或两个参数?如果我需要解释更多,请留下评论,任何帮助都将非常感激:)

向AngularJS模型中添加图片以便上传

我找到了一个解决方案,我将文件和模型添加到表单数据中。所以从这里展开解其实很容易。这是我的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)"/>