后台调用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);
}
|