.net 下webapi上传文件,后台调用方法

后台调用webapi上传文件方法记录下

文件上传接口

[HttpPost]
        public HttpResponseMessage PostFile()
        {
            HttpResponseMessage result = null;
            var httpRequest = HttpContext.Current.Request;
            try
            {
                if (httpRequest.Files.Count > 0)
                {
                    var docfiles = new List<string>();
                    foreach (string file in httpRequest.Files)
                    {
                        var postedFile = httpRequest.Files[file];
                        var filePath = @"F:/llbimg/" + postedFile.FileName;
                        postedFile.SaveAs(filePath);

                        docfiles.Add(filePath);
                    }
                    result = new HttpResponseMessage { Content = new StringContent("true", Encoding.GetEncoding("UTF-8"), "text/plain") };
                }
                else
                {
                    result = new HttpResponseMessage { Content = new StringContent("false,批注上传失败", Encoding.GetEncoding("UTF-8"), "text/plain") };
                }
                return result;
            }
            catch (WebException ex)
            {
                result = new HttpResponseMessage { Content = new StringContent(ex.Response.ToString(), Encoding.GetEncoding("UTF-8"), "text/plain") };
                return result;
            }
        }

后台调用方法

                int l = Request.Files["testdoc"].ContentLength;
                byte[] buffer = new byte[l];
                Stream s = Request.Files["testdoc"].InputStream;
HttpClient client = new HttpClient();
                MultipartFormDataContent form = new MultipartFormDataContent();
                StreamContent fileContent = new StreamContent(s);
                fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
                fileContent.Headers.ContentDisposition.FileName = s_filename;
                form.Add(fileContent);
                HttpResponseMessage res = client.PostAsync("http://192.168.8.9/llb/api/FileUpload/PostFile", form).Result;
                var msg = res.Content.ReadAsStringAsync().Result;
                if (msg.ToString() != "true")
                {
                    return Content(msg);
                }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值