Web Api Self Host大文件上传功能

Web Api 多文件上传功能

还是直接贴代码比较直观

       /// 
        /// 多文件上传接口
        /// 
        /// 
        public async Task Upload(string jobid)
        {
            List resources = new List();
            // 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);
        }

你可能感兴趣的:(C#设计模式,WebApi)