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.
Microsoft.AspNet.WebApi.Cors
, addconfig.EnableCors();
in webapi config and then add[EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")]
to the controller? – Wayne Ellery yesterday