Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm trying to use https://github.com/danialfarid/angular-file-upload to upload an image to my webAPI in a different domain.

My HTML:

<input 
    type="file" 
    ng-file-select="onFileSelect($files)"
    ng-model="imgData" 
    accept="image/*" 
    ng-click="test()" >

My Controller:

app.controller('userController', [ 'removed', '$upload',
function (removed, $upload) {

    $scope.onFileSelect = function ($files) {
        console.log('onFileSelect');  // --------- THIS METHOD DOES NOT FIRE
        $http.post(serviceBase + 'api/person/image', data, {
            withCredentials: true,
            transformRequest: angular.identity
        }).success('ok').error('fail');
    }
    // tried different things from all the resources found online:
    $scope.test = function () {

        // THIS WORKS but how to get the file??
        // successfull call to controller method but unable to retrieve image file inside controller
        $http.post(serviceBase + 'api/person/image', data).then(function (response) {
            return response;
        });

        // unable to call controller method ('Resourse not found', CORS issue?)
        $scope.upload = $upload.upload({
            url: 'person/image', 
            headers: { 'Authorization': 'bearer placeHolderText' },
            file: $scope.imgData,
            ) };

        // unable to call controller method ('Resourse not found', CORS issue?)
        $http.post(serviceBase + 'api/person/image', data, {
            withCredentials: true,
            transformRequest: angular.identity
        }).success('ok').error('fail');}}

API Controller Method:

    [HttpPost()]
    [ActionName("image")]
    [ResponseType(typeof(JObject))]
    public async Task<IHttpActionResult> Postimage(HttpPostedFileBase file)
    {

Update: Enabling CORS details...

My Startup.cs:

  public void Configuration(IAppBuilder app)
    {
        HttpConfiguration config = new HttpConfiguration();

        ConfigureOAuth(app);

        WebApiConfig.Register(config);
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
        app.UseWebApi(config);
    }

    public void ConfigureOAuth(IAppBuilder app)
    {
        //use a cookie to temporarily store information about a user logging in with a third party login provider
        app.UseExternalSignInCookie(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ExternalCookie);
        OAuthBearerOptions = new OAuthBearerAuthenticationOptions();

        OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions() {

            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
            Provider = new SimpleAuthorizationServerProvider(),
            RefreshTokenProvider = new SimpleRefreshTokenProvider()
        };

AuthProvider Class:

  public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin");

        if (allowedOrigin == null) allowedOrigin = "*";

        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

        using (AuthRepository _repo = new AuthRepository())
        {
            IdentityUser user = await _repo.FindUser(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }
        }

        var identity = new ClaimsIdentity(context.Options.AuthenticationType);
        identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
        identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
        identity.AddClaim(new Claim("sub", context.UserName));

        var props = new AuthenticationProperties(new Dictionary<string, string>
            {
                { 
                    "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId
                },
                { 
                    "userName", context.UserName
                }
            });

        var ticket = new AuthenticationTicket(identity, props);
        context.Validated(ticket);

    }

It is most likely that this is a CORS issue because I can post to that controller method using $HTTP.Post. I have enabled CORS on server. I have been reading and trying things for two days and I've hit a brick wall, any suggestions/recommendations are greatly appreciated.

share|improve this question
2  
How did you enable cors? Did you install the nuget package Microsoft.AspNet.WebApi.Cors, add config.EnableCors(); in webapi config and then add [EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")] to the controller? –  Wayne Ellery yesterday
    
First, Thank you! Now... I have updated my question to reflect your comment. Couple of quick notes: config.EnableCors() is in my Startup.cs and I don't yet have [EnableCors(origins: "mywebclient.azurewebsites.net";, headers: "", methods: "")] on my method controller. Is that enough to make a difference? Any call I make using Angular's HTTP.Post works without issues. –  OverMars 12 hours ago
    
I will add [EnableCors(origins: "mywebclient.azurewebsites.net";, headers: "", methods: "")] as soon as I can and see if that works, just seems unlikely since all my calls made with $http work. –  OverMars 12 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.