WebApi获取传来的文件

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 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获取传来的文件)