Web Api Self Host大文件上传功能

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/bj_xuzhiqiang/article/details/73550357

Web Api 多文件上传功能

还是直接贴代码比较直观

       /// <summary>
        /// 多文件上传接口
        /// </summary>
        /// <returns></returns>
        public async Task<IHttpActionResult> Upload(string jobid)
        {
            List<Resource> resources = new List<Resource>();
            // multipart/form-data  
            // 采用MultipartMemoryStreamProvider  
            var provider = new MultipartMemoryStreamProvider();

            //读取文件数据  
            await Request.Content.ReadAsMultipartAsync(provider);

            foreach (var item in provider.Contents)
            {
                // 判断是否是文件  
                if (item.Headers.ContentDisposition.FileName != null)
                {
                    //获取到流  
                    var ms = item.ReadAsStreamAsync().Result;
                    //进行流操作  
                    using (var br = new BinaryReader(ms))
                    {
                        if (ms.Length <= 0)
                            break;
                        //读取文件内容到内存中  
                        var data = br.ReadBytes((int)ms.Length);
                        //Create  
                        //当前时间作为ID  
                        Resource resource = new Resource() { Id = DateTime.Now.ToString("yyyyMMddHHmmssffff", DateTimeFormatInfo.InvariantInfo) };

                        //Info  
                        FileInfo info = new FileInfo(item.Headers.ContentDisposition.FileName.Replace("\"", ""));
                        //文件类型  
                        resource.Type = info.Extension.Substring(1).ToLower();

                        //Write  
                        try
                        {
                            //文件存储地址  
                            string dirPath = Path.Combine(ROOT_PATH);
                            if (!Directory.Exists(dirPath))
                            {
                                Directory.CreateDirectory(dirPath);
                            }

                            File.WriteAllBytes(Path.Combine(dirPath, resource.Id), data);
                            resources.Add(resource);
                        }
                        catch { }
                    }
                }
            }

            //返回  
            if (resources.Count == 0)
                return BadRequest();
            else if (resources.Count == 1)
                return Ok(resources.FirstOrDefault());
            else
                return Ok(resources);
        }

猜你喜欢

转载自blog.csdn.net/bj_xuzhiqiang/article/details/73550357
今日推荐