【发布时间】: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 对象或两个参数中?如果我需要更多解释,请发表评论,任何帮助将不胜感激:)
【问题讨论】: