我需要一些指导,将图像作为带有AngularJS的几个文本字段的表单的一部分上传。我已经查看过web和stackoverflow上的几篇帖子和文章,其中大多数都是自己上传图片或者也不包括Json数据。所以这是我的具体情况:
我有几个相同表单的字段,并希望在用户点击“添加项目”时创建新项目
我需要将文件上传到本地目录“/ images”,并将URL路径+文件名发送到API,其中包含在表单中创建的其余数据。
示例:
我的代码创建了以下发送给API的对象:
{
"title": "Big sale",
"link": "http://www.example.com",
"image": images/entry6.jpg
"id": 1
}
你能帮助我吗?
当前的HTML代码:
<div ng-controller="EditClients" class="container">
<form>
<div class="form-group">
<label>Title</label>
<input type="text" ng-model="newClientsItem.title" required="required" class="form-control"/><br/>
<label>Link</label>
<input type="url" ng-model="newClientsItem.link" required="required" class="form-control"/><br/>
<label>Image</label><br/>
<input type="file" ng-model="newClientsItem.image"/>
<a ng-click="createClientsItem(newClientsItem)" class="btn btn-default btn-lg">Add</a>
</div>
</form>
和JS:
var app = angular.module('app', ['ui.router', 'ngResource', 'ngTagsInput']);
//constants for APIs
app.constant("clientsUrl", "http://www.example.com:3001/api/clients/");
app.controller('EditClients', function($scope, $http, $resource, clientsUrl) {
$scope.clientsItemsResource = $resource(clientsUrl + ":id", {id: "@id"},
{ create : { method: "POST"}, save: { method: "PUT"}}
);
$scope.listClientsItems = function() {
$scope.clientsItems = $scope.clientsItemsResource.query();
};
$scope.deleteClientsItem = function(clientsItem) {
if (confirm('Are you sure you to delete this item?')) {
clientsItem.$delete().then(function () {
$scope.clientsItems.splice($scope.clientsItems.indexOf(clientsItem), 1);
});
}
};
$scope.createClientsItem = function (clientsItem) {
//creates the new item
new $scope.clientsItemsResource(clientsItem).$create().then(function (newClientsItem) {
$scope.clientsItems.push(newClientsItem);
});
};
$scope.updateClientsItem = function(clientsItem) {
clientsItem.$save();
toastr.success('Item sauvé');
};
$scope.listClientsItems();
});