AngularJS angular-file-upload 无法将数据上传到 WebAPI 2 CORS
AngularJS angular-file-upload cannot upload data to WebAPI 2 CORS
我正在尝试使用 https://github.com/danialfarid/angular-file-upload 将图像上传到不同域中的webAPI。
我的网页:
<input
type="file"
ng-file-select="onFileSelect($files)"
ng-model="imgData"
accept="image/*"
ng-click="test()" >
我的控制器:
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 控制器方法:
[HttpPost()]
[ActionName("image")]
[ResponseType(typeof(JObject))]
public async Task<IHttpActionResult> Postimage(HttpPostedFileBase file)
{
**更新:启用 CORS 详细信息...(Microsoft.Owin.Cors) **
我的创业.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()
};
这很可能是 CORS 问题,因为我可以使用 $HTTP.Post 发布到该控制器方法。我已经在服务器上启用了 CORS。我已经阅读和尝试了两天,我遇到了一堵砖墙,任何建议/建议都非常感谢。
更新 2:
又一天的研究/试错:
我可以把它发布:
$scope.upload = $upload.upload({
url: 'http://localhost:26264/api/person/image', //upload.php script, node.js route, or servlet url
file: $scope.imgData,
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
但现在我得到"415(不支持的媒体类型)".. 来自小提琴手的详细信息:
"此资源不支持请求实体的媒体类型'multipart/form-data'。","exceptionMessage":"没有 MediaTypeFormatter 可用于从媒体类型为'multipart/form-data'的内容中读取类型为'HttpPostedFileBase'的对象。
我最终使用了 ng-flow,图像示例有助于进行设置。我还使用它来了解如何读取控制器中的数据,最后用它来保存我的文件。最终解决方案:
控制器:
[HttpPost()]
[ActionName("image")]
[ResponseType(typeof(JObject))]
public async Task<IHttpActionResult> Postimage()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/Content/Images/User");
var provider = new MultipartFormDataStreamProvider(root);
try
{
// Read the form data.
await Request.Content.ReadAsMultipartAsync(provider);
// This illustrates how to get the file names.
foreach (MultipartFileData file in provider.FileData)
{
//Console.WriteLine(file.Headers.ContentDisposition.FileName);
//Trace.WriteLine("Server file path: " + file.LocalFileName);
if (File.Exists(Path.Combine(root, "test.jpg")))
File.Delete(Path.Combine(root, "test.jpg"));
File.Move(file.LocalFileName, Path.Combine(root, "test.jpg"));
return Ok();
}
}
catch (System.Exception e)
{
}
return Ok();
}
角:
app.config(['flowFactoryProvider', function (flowFactoryProvider) {
flowFactoryProvider.defaults = {
target: 'myURL',
permanentErrors: [404, 500, 501],
maxChunkRetries: 1,
chunkRetryInterval: 5000,
simultaneousUploads: 4,
singleFile: true
};
flowFactoryProvider.on('catchAll', function (event) {
console.log('catchAll', arguments);
});
// Can be used with different implementations of Flow.js
// flowFactoryProvider.factory = fustyFlowFactory;
}]);
.HTML:
<div class="form-horizontal" role="form" flow-init
flow-file-added="!!{png:1,gif:1,jpg:1,jpeg:1}[$file.getExtension()]"
flow-files-submitted="$flow.upload()">
<span class="btn-success" flow-btn>Upload Image</span>
</div>
相关文章:
- CORS-重定向到第二个GET正在接收的页面
- node.js请求数据事件未在CORS ajax调用中触发
- 带有凭据的角度文件上载(CORS)不起作用
- 与域在同一台计算机上运行的NODEJS服务器的CORS错误
- SmartGWT数据源和CORS
- CORS-服务器端cookie没有保存在chrome浏览器上
- CORS:否'访问控制允许来源'header-但是php设置头文件
- CORS:访问控制允许原点不等于提供的原点
- CORS保持在SecurityError上:操作不安全
- 绘制(重新加载)具有cors=“”的图像;匿名的“;在画布上(javascript)
- CORS故障无法解决jquery,laravel5.2
- .Net webApi ISO日期时间和IE8
- 在Golang回调函数中启用CORS
- 向localhost发出带有grunt的代理CORS请求
- XMLHttpRequest在$.ajax工作的地方给出了CORS错误
- 遇到400错误请求(Angular+WebAPI)的问题
- 可以'由于CORS问题,无法访问Heroku上的Flask API
- AngularJS angular-file-upload 无法将数据上传到 WebAPI 2 CORS
- 在WebAPI上启用CORS, Chrome和FF仍然不起作用
- AngularJS and WebAPI CORS