我正在尝试从用户那里获取图片并将其上传到我的应用程序中的文件夹中。但是,我的 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"));
我该如何解决这个问题?
您的代码看起来几乎正确,但在设置 Content-Type 时似乎有一个小错误。您需要从 AngularJS 服务方法中删除 headers: { "Content-Type":false } 部分。不要将 Content-Type 设置为 false,而是根本不设置它,让浏览器自动将 Content-Type 设置为 multipart/form-data,这是文件上传所必需的。
您应该如何修改您的服务方法:
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': undefined }, // Modify this line
transformRequest: angular.identity
});
return request;
};
通过设置 'Content-Type': undefined,AngularJS 将删除 content-type 标头,允许浏览器自动设置它,包括设置 multipart/form-data 所需的边界参数。
此外,请确保在您的 Web API 方法中,您正确地从请求中获取文件。为此,您可能需要检查请求中是否有可用文件:
public class ImageUploadApiController : ApiController
{
[HttpPost]
public IHttpActionResult Post()
{
var httpRequest = HttpContext.Current.Request;
// Check if files are available
if (httpRequest.Files.Count > 0)
{
var postedFile = httpRequest.Files[0];
var path = System.Web.Hosting.HostingEnvironment.MapPath("~/UserProfilePic/");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
// Fetch the File Name.
string fileName = Path.GetFileName(postedFile.FileName);
// Save the File.
postedFile.SaveAs(path + fileName);
return Content(HttpStatusCode.OK, fileName);
}
else
{
return BadRequest("No files to upload.");
}
}
}
这应该可以解决 HttpContext.Current.Request.Files 计数为零的问题。尝试进行这些调整,您的文件上传应该可以正常工作。