WebAPI Angularjs 上传文件

时间:2023-03-09 13:22:26
WebAPI Angularjs 上传文件

直接上代码

HTML页面代码:

<label>资源URL</label>
<input type="text" class="form-control" id="txtSourceURL" name="txtSourceURL"
          ng-model="editdata.SourceURL" placeholder="资源URL" ng-maxlength="500">
<!--文件地址展示-->
  
<button id="chooseFile" onclick="$('#fileUpload').click()">选择文件上传</button>
<!--加这个控件是实现选择文件上传文件功能,减少页面上控件的数量,方便样式的调整-->

<input id="fileUpload" type="file" onchange="$('#uploads').click()" style="display: none;" />
<!--浏览器自带的上传文件控件,我也想过change事件直接调用save()方法,但是好像不管用,我只好通过这种中转调用了,大家有知道的告诉我-->
<button ng-click="save()" id="uploads" style="display: none;">确定上传</button>
<!--必须使用其他控件(按钮或者标签)调用上传(save())方法-->

controller.js代码

    app.controller('editController', ['$scope', "$http", 'webConfig', function ($scope, $http, webConfig) {
$scope.save = function () {
var fd = new FormData();
var file = document.querySelector('input[type=file]').files[0];
fd.append('logo', file); //angular 上传的文件必须使用特殊的格式处理,不是json格式
$http({
method: 'POST',
url: webConfig.apiRoot + "/api/ECategoryDetail/PostFiles", //"https://localhost:44320//api/ECategoryDetail/PostFiles"
data: fd,
headers: { 'Content-Type': undefined }, // 写成是undifined,浏览器才自动转化为 文件上传的类型
transformRequest: angular.identity
}).success(function (response) {
//上传成功的操作
if (response.mark) //接口返回的数据标志位,是否保存成功,保存成功则把文件相对地址更新到实体中
$scope.editdata.SourceURL = response.result;
else
alert("上传失败");
});
};
}]);

webapi代码:

        /// <summary>
/// 上传文件
/// </summary>
[HttpPost, Route("api/ECategoryDetail/PostFiles")]
public IHttpActionResult PostFiles()
{
var result = "";
var filelist = HttpContext.Current.Request.Files;
var mark = true;
if (filelist.Count > )
{
for (var i = ; i < filelist.Count; i++)
{
var file = filelist[i];
var fileName = file.FileName;
var virtualPath = "/UploadFile/Files/";
var path = HttpContext.Current.Server.MapPath(virtualPath);//文件全路径
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
var filePath = $"{path }{fileName}";
try
{
file.SaveAs(filePath);
result = $@"{virtualPath}{fileName}";
}
catch (Exception ex)
{
result = "上传文件写入失败:" + ex.Message;
mark = false;
}
}
}
else
{
result = "上传的文件信息不存在!";
mark = false;
} var json = new { result, mark };
return Ok(json);
}

有疑问欢迎交流。