我正在想办法。我的代码没有得到任何有用的错误消息,因此我使用其他代码来生成一些错误消息。我在错误消息后附加了该代码。我已经找到了一个 教程上,但我不知道如何实施它与我有什么。这是我目前拥有的:
public async Task<object> PostFile()
{
if (!Request.Content.IsMimeMultipartContent())
throw new Exception();
var provider = new MultipartMemoryStreamProvider();
var result = new { file = new List<object>() };
var item = new File();
item.CompanyName = HttpContext.Current.Request.Form["companyName"];
item.FileDate = HttpContext.Current.Request.Form["fileDate"];
item.FileLocation = HttpContext.Current.Request.Form["fileLocation"];
item.FilePlant = HttpContext.Current.Request.Form["filePlant"];
item.FileTerm = HttpContext.Current.Request.Form["fileTerm"];
item.FileType = HttpContext.Current.Request.Form["fileType"];
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var user = manager.FindById(User.Identity.GetUserId());
item.FileUploadedBy = user.Name;
item.FileUploadDate = DateTime.Now;
await Request.Content.ReadAsMultipartAsync(provider)
.ContinueWith(async (a) =>
{
foreach (var file in provider.Contents)
{
if (file.Headers.ContentLength > 1000)
{
var filename = file.Headers.ContentDisposition.FileName.Trim('\"');
var contentType = file.Headers.ContentType.ToString();
await file.ReadAsByteArrayAsync().ContinueWith(b => { item.FilePdf = b.Result; });
}
}
}).Unwrap();
db.Files.Add(item);
db.SaveChanges();
return result;
}
错误:
对象{ message: “此资源不支持请求实体的媒体类型‘ multipart/form-data’。”“没有 MediaTypeFormatter 可用于读取媒体类型为‘ multipart/form-data’的 obje... om 内容。”例外类型:”系统。网。哈哈。不支持的 MediaTypeException”,stackTrace: “ at System。网。哈哈。HttpContentExtended.ReadAs... atterLogger,CcellationToken CancellationToken)”} exctionMessage: “没有 MediaTypeFormatter 可用于从媒体类型为‘ multipart/form-data’的内容中读取类型为‘ HttpPostedFileBase’的对象。异常类型: 系统。网。哈哈。“信息:”此资源不支持请求实体的媒体类型‘ multipart/form-data’。“ stackTrace:”at System。网。哈哈。HttpContentExtended.ReadAsAsync [ T ](HttpContent content,Type Type,IEnumable < code > 1 format ters,IFormatterLogger format terLogger,CancelationToken CancellationToken) ReadAsAsync (HttpContent 内容,类型,IEnumable 1格式化程序,IFormatterLogger 格式化程序,取消令牌取消令牌)
用于生成错误消息的代码:
[HttpPost]
public string UploadFile(HttpPostedFileBase file)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(HttpContext.Current.Server.MapPath("~/uploads"), fileName);
file.SaveAs(path);
}
return "/uploads/" + file.FileName;
}
班级:
public class File
{
public int FileId { get; set; }
public string FileType { get; set; }
public string FileDate { get; set; }
public byte[] FilePdf { get; set; }
public string FileLocation { get; set; }
public string FilePlant { get; set; }
public string FileTerm { get; set; }
public DateTime? FileUploadDate { get; set; }
public string FileUploadedBy { get; set; }
public string CompanyName { get; set; }
public virtual ApplicationUser User { get; set; }
}