2015-02-06 212 views
29

我想弄清楚如何完成这件事。我没有收到任何有用的错误消息,因此我使用了其他的东西来生成一些东西。我在错误消息后附加了该代码。我发现了一个tutorial,但我不知道如何使用我的东西来实现它。这是我目前有如何设置multipart/form-data的webapi控制器

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的' 不支持这个资源。”,exceptionMessage:“不MediaTypeFormatter可用于读取媒体类型为'multipart/form-data'的对象内容。“,exceptionType:”System.Net.Http.UnsupportedMediaTypeException“,stackTrace:”at System.Net.Http.HttpContentExtensions.ReadAs ... atterLogger ,CancellationToken cancellationToken)“} exceptionMessage:”没有MediaTypeFormatter可用于从媒体类型为'multipart/form-data'的内容中读取'HttpPostedFileBase'类型的对象。“exc eptionType:“System.Net.Http.UnsupportedMediaTypeException”消息:“请求实体的媒体类型'multipart/form-data'不支持此资源。”stackTrace:“at System.Net.Http.HttpContentExtensions.ReadAsAsync [T] (HttpContent内容,类型类型,IEnumerable的1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken) ↵ at System.Net.Http.HttpContentExtensions.ReadAsAsync(HttpContent content, Type type, IEnumerable 1格式化器,IFormatterLogger formatterLogger,的CancellationToken的CancellationToken)

代码用于生成错误消息

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

因此,它看起来像你从一个后端到另一个POST-ING的数据。你使用multipart/form而不是JSON或原始数据的原因是什么? – timothyclifford 2015-02-06 16:10:33

+0

没有理由,这是我后来的工作。我张贴我的角度。我打开建议 – texas697 2015-02-06 16:13:57

回答

59

我通常使用HttpPostedFileBase参数只在Mvc控制器。当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; 
} 
+0

这是错误信息。无法找到路径'C:\ Development \ Transp \ temp \ uploads \ 02-Unicare.PNG'的一部分。 – texas697 2015-02-06 17:52:57

+0

权限是通过使用Windows文件浏览器设置的? – texas697 2015-02-06 17:53:37

+0

现在看来你用来保存接收文件的路径是无效的。检查该文件夹是否存在,并确保您的应用程序对该文件夹具有读/写权限(是的,您可以使用Windows资源管理器执行此操作)。 – 2015-02-06 17:58:07

12

您可以使用类似这样

[HttpPost] 
public async Task<HttpResponseMessage> AddFile() 
{ 
    if (!Request.Content.IsMimeMultipartContent()) 
    { 
     this.Request.CreateResponse(HttpStatusCode.UnsupportedMediaType); 
    } 

    string root = HttpContext.Current.Server.MapPath("~/temp/uploads"); 
    var provider = new MultipartFormDataStreamProvider(root); 
    var result = await Request.Content.ReadAsMultipartAsync(provider); 

    foreach (var key in provider.FormData.AllKeys) 
    { 
     foreach (var val in provider.FormData.GetValues(key)) 
     { 
      if (key == "companyName") 
      { 
       var companyName = val; 
      } 
     } 
    } 

    // On upload, files are given a generic name like "BodyPart_26d6abe1-3ae1-416a-9429-b35f15e6e5d5" 
    // so this is how you can get the original file name 
    var originalFileName = GetDeserializedFileName(result.FileData.First()); 

    var uploadedFileInfo = new FileInfo(result.FileData.First().LocalFileName); 
    string path = result.FileData.First().LocalFileName; 

    //Do whatever you want to do with your file here 

    return this.Request.CreateResponse(HttpStatusCode.OK, originalFileName); 
} 

private string GetDeserializedFileName(MultipartFileData fileData) 
{ 
    var fileName = GetFileName(fileData); 
    return JsonConvert.DeserializeObject(fileName).ToString(); 
} 

public string GetFileName(MultipartFileData fileData) 
{ 
    return fileData.Headers.ContentDisposition.FileName; 
} 
+0

你能告诉我我需要在这里做什么。我不太明白 – texas697 2015-02-06 16:31:37

+0

上述代码将保留在接受multipart/form-data的Web API控制器中。一旦代码验证其多部分内容,我们就会得到文件和额外的数据,如“公司名称”,...您可以处理您的文件,保存并返回所需的结果。你可以使用角度/ .net代码来访问这个方法 – 2015-02-06 16:42:57

+0

我插入了你必须看到发生了什么,但它会在第一个foreach循环中抛出错误。部分问题是我不太明白它是如何转换为二进制格式。我创建了tmp文件夹并确保它具有写入权限 – texas697 2015-02-06 17:38:59

2

检查乌尔WebApiConfig并添加此

GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); 
+0

这似乎没有在我的情况下工作;然而。 – user1477388 2015-12-10 20:17:31

-2

你得到HTTP 415“请求实体的中介此资源不支持“multipart/form-data”类型。“因为您没有在您的请求中提及正确的内容类型。

+0

小心添加更多解释?我不知道如何解决这个问题。 – frostymarvelous 2017-04-25 15:33:33

11

这是解决我的问题
以下行添加到WebApiConfig.cs

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