美文网首页
WebApi获取传来的文件

WebApi获取传来的文件

作者: 梦的方向叫闯_aa65 | 来源:发表于2018-06-05 16:15 被阅读0次

    1、如果是以文件的形式上传,这样接收:

      public IHttpActionResult getTest2()
            {
                string id = HttpContext.Current.Request["id"];
                string name = HttpContext.Current.Request["name"];
                HttpFileCollection files = HttpContext.Current.Request.Files; 
                foreach (string key in files.AllKeys)
                {
                    HttpPostedFile file = files[key];//file.ContentLength文件长度  
                    if (string.IsNullOrEmpty(file.FileName) == false)
                        file.SaveAs(HttpContext.Current.Server.MapPath("~/App_Data/")  + file.FileName);
                }
                return Ok("success2");
            }
    

    2、如果是以文件流的形式上传(如从Android端使用retrofit上传多文件),这样接收:

     [HttpPost]
            public async Task<string> InsertPics()
            {   var root = HttpContext.Current.Server.MapPath("~/App_Data");
                var provider = new MultipartFormDataStreamProvider(root);
                await Request.Content.ReadAsMultipartAsync(provider);
                var httpContents = provider.Contents;
                int i = 0;
                foreach (var content in httpContents)
                {
                    var suffix =  content.Headers.ContentDisposition.Name.Trim('"').Split('.').Last();
                    var arrayAsync = content.ReadAsByteArrayAsync();
                    FileStream stream = new FileStream(root + "\\" + i++ + "." +  suffix, FileMode.CreateNew);
                    stream.Write(arrayAsync.Result, 0, arrayAsync.Result.Length);
                    stream.Close();
                }
                return null;
            }
    

    相关文章

      网友评论

          本文标题:WebApi获取传来的文件

          本文链接:https://www.haomeiwen.com/subject/ohqmsftx.html