欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Web Api Self Host大文件上传功能

程序员文章站 2024-02-20 10:59:04
...

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);
        }