webapi上传示例及调用方式

调用事件(方法):

  protected void btn_Click(object sender, EventArgs e)
        {
            using (var client = new HttpClient())
            using (var content = new MultipartFormDataContent())
            {
                // Make sure to change API address  
                client.BaseAddress = new Uri("http://192.168.199.102:8027/");

                // Add first file content   
                var fileContent1 = new ByteArrayContent(File.ReadAllBytes(@"D:\文件上传\BIMAPI测试数据.txt"));
                fileContent1.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = "BIMAPI测试数据.txt"
                };

                // Add Second file content  
                var fileContent2 = new ByteArrayContent(File.ReadAllBytes(@"D:\文件上传\WebDeploy发布.png"));
                fileContent2.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = "WebDeploy发布.png"
                };

                content.Add(fileContent1);
                content.Add(fileContent2);

                // Make a call to Web API  
                var result = client.PostAsync("/api/file/FilePost2", content).Result;
                txtResult.Text = result.StatusCode.ToString();
             //   Console.WriteLine(result.StatusCode);
             // Console.ReadLine();
            }
        }

WebApi文件上传接口

  #region 上传文件
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>
        public async Task<HttpResponseMessage> FilePost2()
        {          
            //指定要将文件存入的服务器物理位置,如果路径不存在,创建路径
            if (!Directory.Exists(FileUrl))
            {
                Directory.CreateDirectory(FileUrl);
            }
            //检查请求中是否包含multipart/form-data,即文件上传请求
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
            //初始化MultipartFormDataStreamProvider实例
            CustomMultipartFormDataStreamProvider provider = new CustomMultipartFormDataStreamProvider(FileUrl);
            List<string> files = new List<string>();
            try
            {
                // 读取文件上传
                await Request.Content.ReadAsMultipartAsync(provider);
              //获取已上传的文件名
                foreach (MultipartFileData file in provider.FileData)
                {
                    //接收文件
                     files.Add(Path.GetFileName(file.LocalFileName));
                }
                return Request.CreateResponse(HttpStatusCode.OK, files);
            }
            catch(Exception e)
            {             
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
            }        
        }
        #endregion


        public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
        {
            public CustomMultipartFormDataStreamProvider(string path) : base(path) { }

            public override string GetLocalFileName(HttpContentHeaders headers)
            {
                return headers.ContentDisposition.FileName.Replace("\"", string.Empty);
            }
        }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值