[英]File Upload angular js with web API on different server
我有一个 angular 应用程序,我想使用部署在不同服务器上的 web api 上传文件。
实际上,我准备了一个在 web api 上包含 html 的示例,并且我成功地将文件上传到了他们的文件,但是一旦我尝试将它从我的 angular 应用程序上传到不同的服务器(跨源而不是失败),我就实现了跨源支持也。
注意:我正在为文件上传进行 ajax 调用。
<html data-ng-app="MyApp">
<head>
<link rel="stylesheet" href="Styles/bootstrap.min.css">
<title>Index</title>
<script src="Scripts/angular-cookies.js" type="text/javascript"></script>
<script src="Scripts/angular-route.min.js" type="text/javascript"></script>
<script src="Scripts/angular.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
debugger;
$(document).ready(function () {
$("#button1").click(function (evt) {
var files = $("#file1").get(0).files;
if (files.length > 0) {
var data = new FormData();
for (i = 0; i < files.length; i++) {
data.append("file" + i, files[i]);
}
$.ajax({
type: "POST",
url: "http://localhost/WebApi/api/Fileupload/Post",
contentType: false,
crossorigin: true,
processData: false,
data: data,
success: function (messages) {
for (i = 0; i < messages.length; i++) {
alert(messages[i]);
}
},
error: function () {
alert("Error while invoking the Web API");
}
});
}
});
});
</script>
</head>
<body>
<!-- form name and controller declare -->
<form>
<span>Select file(s) to upload :</span>
<input id="file1" name="file1" type="file" multiple="multiple" />
<input id="button1" type="button" value="Upload" />
</form>
</body>
</html>
如果我的问题正确,您使用的是Microsoft's ASP.NET MVC WebAPI
。 在这种情况下,您应该使用EnableCORS
选项并将其设置在您的WebAPI config
,如下所示:
步骤: 1. 在包管理器控制台中为 CORS 安装 Nuget 作为
Install-Package Microsoft.AspNet.WebApi.Cors
2.添加config.EnableCors
在WebApiConfig
public static void Register(HttpConfiguration config)
{
config.EnableCors();
}
3. 在您的控制器中添加 EnableCors 属性,如下所示:
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class ValueController : ApiController
有关更多详细信息,请参阅: http : //www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
默认情况下,您遇到的是浏览器安全功能,该功能会阻止对其他 Web 资源的 http 请求
如果添加标志Access-Control-Allow-Origin
,则可以更改此默认行为; Web 应用程序服务器响应中的Access-Control-Allow-Methods
包括允许的来源(资源)
您没有指定正在使用的 Web 应用程序软件(asp.net、django、node.js 等)但是例如,这就是您在django 中支持它的方式
很早以前在网上找过,找到了一种在网上上传Angular App的方法。 您需要在Vercel.com
上拥有一个帐户(它是免费的),然后在 Angular 的项目文件夹中编写以下命令:
1- ng build --prod //Generate the dist folder
2- npm install -g now //install the tool
3- now //in our directory "dist\"
4- Set up and deploy -> Yes
5- Introduce our Vercel account
6- Link proyect -> No
7- Set proyect name //Enter, dont write nothing
8- Override settings -> Yes
9- Choose -> Build Command
最后,您将获得一个在.now.sh
完成的链接。 从您的 Internet Explorer 中的任何设备打开此链接,您将在 Internet 上拥有您的应用程序。
PS:在vercel.com
您可以更改 DNS 等,因为如果您有域,则可以将 url ( http:/.....now.sh
) 更改为您想要的。
此方法在 Angular 8 和 9 中测试没有问题。
这是我的第一篇文章,希望能帮到很多人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.