这次的需求是请求java那边的一个excel批量上传的接口。但是他们的接口要求是这样的
于是自己写了个方法:
调用:
控制器层
var file = this.HttpContext.Request.Files[0];//获取前端传来的文件
var fileName = file.FileName;//注意:Stream不能做参数传,所以转成byte用来传值
byte[] fileByte = FileUtil.StreamToBytes(file.InputStream);
代理层
IOscarResult result = new IOscarResult();
try
{Dictionary<string, string> headerDict = new Dictionary<string, string>();
headerDict.Add("userId", 54000); //header userid
NameValueCollection par = new NameValueCollection();
par.Add("dataSource", "数据源"); //数据源
dynamic fileInfo = new ExpandoObject();
fileInfo.fileName = fileName; //文件名
fileInfo.fileByte = fileByte; //文件字节
fileInfo.file = "file"; //字段名
//请求
string response = WebApiProxy.PostMultipartFormDataAsync(NodeName.IOscarBaseSystemApi, "extends/rpc/org/upload", headerDict, par, fileInfo);
result = JsonConvert.DeserializeObject<IOscarResult>(response);
}
catch (System.Exception ex)
{
result.Success = false;
result.Msg = "异常:" + ex.ToString();
}
//http请求方法:
/// <summary>
/// 使用multipart/form-data方式上传文件及其他数据
/// </summary>
/// <param name="requestUrl">请求接口地址</param>
/// <param name="headers">自定义header</param>
/// <param name="nameValueCollection">键值对参数</param>
/// <param name="fileInfo">文件信息</param>
/// <returns></returns>
public static string PostMultipartFormDataAsync( string requestUrl, Dictionary<string, string> headers, NameValueCollection nameValueCollection, dynamic fileInfo)
{
var data = "";
using (var httpClient = new HttpClient())
{
try
{//header参数
foreach (var item in headers)
{
httpClient.DefaultRequestHeaders.Add(item.Key, item.Value);
}using (var reduceAttach = new MultipartFormDataContent())
{
#region 键值对参数
string[] allKeys = nameValueCollection.AllKeys;
foreach (string key in allKeys)
{
var dataContent = new ByteArrayContent(Encoding.UTF8.GetBytes(nameValueCollection[key]));
dataContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = key
};
reduceAttach.Add(dataContent);
}
#endregion#region 文件参数
if (fileInfo != null)
{
Stream fileStream = FileUtil.BytesToStream(fileInfo.fileByte);//转成stream流
var streamContent = new StreamContent(fileStream);
var Content = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result);//创建文件的content
reduceAttach.Add(Content, fileInfo.file, fileInfo.fileName);
streamContent.Dispose();
}
#endregion//请求
var response = httpClient.PostAsync(requestUrl, reduceAttach).Result;
data = response.Content.ReadAsStringAsync().Result;
}
}
catch (Exception ex)
{
throw ex;
}
}
return data;
}
/// 将 Stream 转成 byte[]
public static byte[] StreamToBytes(Stream stream)
{
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
// 设置当前流的位置为流的开始
stream.Seek(0, SeekOrigin.Begin);
return bytes;
}/// 将 byte[] 转成 Stream
public static Stream BytesToStream(byte[] bytes)
{
Stream stream = new MemoryStream(bytes);
return stream;
}