如何设置的WebAPI控制器的multipart / form-data的 [英] How to setup a webapi controller for multipart/form-data

查看:17444
本文介绍了如何设置的WebAPI控制器的multipart / form-data的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出如何得到这个工作。我没有得到任何有用的错误信息与我的code,所以我用别的东西来产生的东西。我附上错误消息后code。我发现了一个教程上,但我不知道怎么跟我有什么实现它。这是我目前有

 公共异步任务<对象> PostFile()
    {
        如果(!Request.Content.IsMimeMultipartContent())
            抛出新的异常();
        VAR提供商=新MultipartMemoryStreamProvider();
        VAR的结果=新{文件=新的List<对象>()};
        VAR项目=新的文件();        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 [文件类型];        VAR经理=新的UserManager< ApplicationUser>(新UserStore< ApplicationUser>(新ApplicationDbContext()));
        变种用户= manager.FindById(User.Identity.GetUserId());        item.FileUploadedBy = user.Name;
        item.FileUploadDate = DateTime.Now;        等待Request.Content.ReadAsMultipartAsync(供应商)
         .ContinueWith(异步(一)= GT;
         {
             的foreach(在provider.Contents var文件)
             {
                 如果(file.Headers.ContentLength> 1000)
                 {
                     变种文件名= file.Headers.ContentDisposition.FileName.Trim('\\');
                     变种的contentType = file.Headers.ContentType.ToString();
                     。等待file.ReadAsByteArrayAsync()ContinueWith(B = GT; {item.FilePdf = b.Result;});
                 }
             }
         })展开()。        db.Files.Add(项目);
        db.SaveChanges();
        返回结果;    }

错误


  

对象{消息:请求实体的媒体类型的multipart / form-data的不支持此资源,exceptionMessage:没有MediaTypeFormatter可用来读取OBJE ...有机质含量与媒体类型多部分/窗体。-data',exceptionType:System.Net.Http.UnsupportedMediaTypeException,堆栈跟踪:在System.Net.Http.HttpContentExtensions.ReadAs ... atterLogger,的CancellationToken的CancellationToken)} exceptionMessage:没有MediaTypeFormatter可读取对象。System.Net.Http.UnsupportedMediaTypeException消息:从媒体类型的multipart / form-data的'exceptionType内容类型HttpPostedFileBase的要求实体的媒体类型的multipart / form-data的不支持此资源堆栈跟踪:在System.Net.Http.HttpContentExtensions.ReadAsAsync [T](HttpContent内容,类型类型的IEnumerable 1格式化,IFormatterLogger formatterLogger,的CancellationToken的CancellationToken)
  ↵在System.Net.Http.HttpContentExtensions.ReadAsAsync(HttpContent内容,类型类型的IEnumerable
1格式化,IFormatterLogger formatterLogger,的CancellationToken的CancellationToken)


code用于生成错误信息

  [HttpPost]
    公共字符串UploadFile(HttpPostedFileBase文件)
    {        如果(file.ContentLength大于0)
        {
            变种文件名= Path.GetFileName(file.FileName);
            VAR路径= Path.Combine(HttpContext.Current.Server.MapPath(〜/上传),文件名);
            file.SaveAs(路径);
        }
        返回/上传/+ file.FileName;
    }

 公共类文件
{
    公众诠释FILEID {搞定;组; }
    公共字符串的文件类型{搞定;组; }
    公共字符串FILEDATE {搞定;组; }
    公共字节[] {FilePdf获得;组; }
    公共字符串FileLocation {搞定;组; }
    公共字符串FilePlant {搞定;组; }
    公共字符串FileTerm {搞定;组; }
    公众的DateTime? FileUploadDate {搞定;组; }
    公共字符串FileUploadedBy {搞定;组; }    公共字符串公司名称{搞定;组; }
    公共虚拟ApplicationUser用户{搞定;组; }
}


解决方案

我通常使用在 HttpPostedFileBase 参数仅在 MVC控制器。当处理的 ApiControllers 尝试检查在 HttpContext.Current.Request.Files 属性传入的文件,而不是:

  [HttpPost]
公共字符串UploadFile()
{
    var文件= HttpContext.Current.Request.Files.Count> 0?
        HttpContext.Current.Request.Files [0]:空;    如果(文件= NULL&放大器;!&安培; file.ContentLength大于0)
    {
        变种文件名= Path.GetFileName(file.FileName);        VAR路径= Path.Combine(
            HttpContext.Current.Server.MapPath(〜/上传),
            文件名
        );        file.SaveAs(路径);
    }    返回文件!= NULL? /上传/+ file.FileName:空;
}

I am trying to figure out how to get this done. I was not getting any useful error messages with my code so I used something else to generate something. I have attached that code after the error message. I have found a tutorial on it but I do not know how to implement it with what I have. This is what i currently have

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;

    }

error

Object {message: "The request entity's media type 'multipart/form-data' is not supported for this resource.", exceptionMessage: "No MediaTypeFormatter is available to read an obje…om content with media type 'multipart/form-data'.", exceptionType: "System.Net.Http.UnsupportedMediaTypeException", stackTrace: " at System.Net.Http.HttpContentExtensions.ReadAs…atterLogger, CancellationToken cancellationToken)"}exceptionMessage: "No MediaTypeFormatter is available to read an object of type 'HttpPostedFileBase' from content with media type 'multipart/form-data'."exceptionType: "System.Net.Http.UnsupportedMediaTypeException"message: "The request entity's media type 'multipart/form-data' is not supported for this resource."stackTrace: " at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken) ↵ at System.Net.Http.HttpContentExtensions.ReadAsAsync(HttpContent content, Type type, IEnumerable1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)

Code used to generate error message

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

class

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

解决方案

I normally use the HttpPostedFileBase parameter only in Mvc Controllers. When dealing with ApiControllers try checking the HttpContext.Current.Request.Files property for incoming files instead:

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

这篇关于如何设置的WebAPI控制器的multipart / form-data的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆