调用事件(方法):
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);
}
}