首页 > 解决方案 > 使用 AngularJS 将图像上传到 Web Api

问题描述

嗨,我是 Web API 的新手,我正在使用 AngularJS 和 Web API 我正在尝试将图像上传到 Web API,但是当我单击按钮发送图像时,它给了我一个错误

我已经使用了 GET 方法,它向我显示了该 Web API 中的所有图像,但它不适用于 POST 方法

这是我的代码

索引.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title> 
    <link rel="stylesheet" href="css/bootstrap.css" media="screen"> 
    <link rel="stylesheet" href="css/bootswatch.min.css">
</head>
<body> 
<div ng-app="MarcasApp" >
    <div ng-controller="MarcaController">
        <div class="container">
            <h2>Muestra</h2>
        </div>
    <input type="button" class="btn btn-info"  value="Todos" ng-click="getTodos()">

    <form name="formulario" method="post" action="" enctype="multipart/form-data">
        <div class="container">
            <label for="caption">Id:</label> 
            <input type="input" class="form-control" ng-model="txtId"/>
        </div>
        <div class="container">
            <label for="caption">Cargar Marcar:</label>  
            <input type="file" ng-files="getTheFiles"/>
        </div><br>  
        <div class="container">
            <input type="submit" value="Enviar Marca" class="btn btn-success" 
            ng-click="btnGuardar()"/>
        </div><br>
        <div class="container">
            Mensaje:{{msgGuardar}}
        </div>
    </form>

    <div class="panel panel-info">
        <ul class="list-group" ng-repeat="marca in marcas">
            <li class="list-group-item">
                <img src="{{marca.imagen}}">
                {{marca.marca1}} + {{marca.marcaId}}
            </li>           
        </ul>
    </div>
    </div>
</div>

<script src="js/jquery.min.js"></script>
<script src="js/angular.min.js"></script>
<script src="MarcaJson.js"></script>

 </body>
</html>

MarcaJson.js

var app = angular
    .module("MarcasApp", [])
    .controller("MarcaController", function($scope, $http){
        $scope.getTodos =function(){
            var apiUrl = 'http://tiendawebapi.azurewebsites.net/api/marcas/';
            $http.get(apiUrl).then(function(response){
            $scope.marcas =  response.data;
            });
        };

        $scope.btnGuardar = function(){
            var datos = {
                id: $scope.txtId,
                imagen: $scope.getTheFiles
            }

            var apiUrl = 'http://tiendawebapi.azurewebsites.net/api/marcas/';
            $http.post(apiUrl, JSON.stringify(datos)).then(function(response){
                if  (response.statusText == Created){
                    $scope.msgGuardar = "Marca Guardada";
                }
            }, function(error){
                $scope.msgGuardar = "Ocurrio un error " + error.statusText;
            });
        };
    });

标签: angularjsapi

解决方案


推荐阅读