HttpContext 请求文件计数即将归零

HttpContext Request Files Count is coming zero

提问人:Maryam 提问时间:11/2/2023 最后编辑:Peter MortensenMaryam 更新时间:11/5/2023 访问量:60

问:

我正在尝试从用户那里获取图片并将其上传到我的应用程序中的文件夹。但是,我的文件计数在我的 Web API 中为零。因此,我无法将其上传到文件夹。

我正在使用 AngularJS 和 MVC Web API 控制器。

我的输入控件是:

<input type="file" valid-file upload="uploadFile(file)" ng-model="file">

指令如下:

app.directive('validFile', [function () {
    return {
        require: 'ngModel',
        scope: { format: '@', upload: '&upload' },
        link: function (scope, el, attrs, ngModel) {
            // Change event is fired when file is selected
            el.bind('change', function (event) {
                console.log(event.target.files[0]);
                scope.upload({ file: event.target.files[0] });
                scope.$apply(function () {
                    ngModel.$setViewValue(el.val());
                    ngModel.$render();
                });
            })
        }
    }
}]);

控制器方法如下:

var PromiseData = UserService.uploadProfilePicture(file);

PromiseData.then(function (Response) {
    alertify.alert('Picture Uploaded Sucessfully');
    $scope.ProfilePicturePath = response.data;

}, function (Error) {
    alertify.alert('Some issue occurred while saving picture');
});

调用 Web API 的服务方法如下:

this.uploadProfilePicture = function (ProfilePicture) {
    var formData = new FormData();
    formData.append('file', ProfilePicture);
    var request = $http({
        method: "post",
        url: "/api/ImageUploadApi",
        data: formData,
        headers: { "Content-Type":false }
    });
    return request;
};

用于上传文件的图像上传 API 如下所示,其中 HttpContext.Current.Request.Files 计数为

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;

namespace UAECensus.Controllers
{
    public class ImageUploadApiController : ApiController
    {
        [HttpPost]
        public IHttpActionResult Post()
        {
            var path = System.Web.Hosting.HostingEnvironment.MapPath("~/UserProfilePic/");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            HttpPostedFile postedFile = HttpContext.Current.Request.Files[0];

            // Fetch the file name.
            string fileName = Path.GetFileName(postedFile.FileName);

            // Save the file.
            postedFile.SaveAs(path + fileName);
            return Content(HttpStatusCode.OK, fileName);
        }

    }
}

此外,我在 AppStart 文件夹中的 WebApiConfig.cs 中添加了以下行:

config.Formatters.XmlFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data"));

我该如何解决这个问题?

javascript asp.net angularjs asp.net-web-api 文件上传

评论

0赞 Naila Akbar 11/3/2023
你检查过吗??headers: { "Content-Type":multipart/form-data }
0赞 Peter Mortensen 11/5/2023
Re “AngularJS”:AngularJS 很古老。 你是说 Angular 吗?

答: 暂无答案