小编典典

如何为多部分/表单数据设置Web API控制器

c#

我正在尝试解决这个问题。我的代码没有得到任何有用的错误消息,因此我使用了其他东西来生成东西。错误消息后,我已附加了该代码。我已经找到了有关它的教程,但是我不知道如何使用现有的方法来实现它。这是我目前拥有的:

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;

    }

错误:

对象{消息:此资源不支持请求实体的媒体类型’multipart / form-
data’。”,异常消息:“没有MediaTypeFormatter可用于读取媒体类型为’multipart / form-
data’的对象内容。“,exceptionType:“
System.Net.Http.UnsupportedMediaTypeException”,stackTrace:“在System.Net.Http.HttpContentExtensions.ReadAs…atterLogger,CancellationToken取消令牌)”}
exceptionMessage:“没有MediaTypeFormatter可用于读取类型为’ ”。ExceptionType:“
System.Net.Http.UnsupportedMediaTypeException”消息:“此资源不支持请求实体的媒体类型“ multipart
/ form-data”。”堆栈跟踪: ”在System.Net.Http.HttpContentExtensions.ReadAsAsync
[T](HttpContent内容,类型,IEnumerable1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken) ↵ at System.Net.Http.HttpContentExtensions.ReadAsAsync(HttpContent content, Type type, IEnumerable1个格式化程序,IFormatterLogger
formatterLogger,CancellationToken取消Token)

用于生成错误消息的代码:

    [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; }
}

阅读 460

收藏
2020-05-19

共1个答案

小编典典

我通常只在 Mvc Controllers中* 使用 HttpPostedFileBase 参数。在处理 ApiControllers
时, 尝试检查 HttpContext.Current.Request.Files 属性是否包含传入文件:
*

[HttpPost]
public string UploadFile()
{
    var file = HttpContext.Current.Request.Files.Count > 0 ?
        HttpContext.Current.Request.Files[0] : null;

    if (file != null && file.ContentLength > 0)
    {
        var fileName = Path.GetFileName(file.FileName);

        var path = Path.Combine(
            HttpContext.Current.Server.MapPath("~/uploads"),
            fileName
        );

        file.SaveAs(path);
    }

    return file != null ? "/uploads/" + file.FileName : null;
}
2020-05-19