最近在使用C# httpClient工具上传文件时,文件名为中文出现乱码的情况。部分代码如下
using (var content = new MultipartFormDataContent())
{
var stream = System.IO.File.OpenRead(filePath);
var streamContent = new StreamContent(new FileStream(filePath, FileMode.Open, FileAccess.Read));
content.Add(streamContent, "files[]", info.Name);
var collections = new NameValueCollection();
collections.Add("\"archtypeid\"", #34;{archtypeid}");
collections.Add("\"archid\"", #34;{data["id"]}");
collections.Add("\"tableid\"", #34;{tableid}");
collections.Add("\"pl\"", #34;yes");
collections.Add("\"userID\"", #34;{ConfigManage.Instance.UserId}");
int time = ConvertDateTimeInt(DateTime.Now);
collections.Add("\"timestamp\"", time.ToString());
var formDatas = this.GetFormDataByteArrayContent(collections);
foreach (var temp in formDatas)
{
content.Add(temp);
}
var result = HttpClientHelper.Instance.Post(#34;Archive/ErecordManage/upload.html", content, null, null);
if (int.TryParse(result.ToString(), out int val) && val == 1)
{
//上传成功
isUpLoadSucc = true;
}
}
/// <summary>
/// 获取键值集合对应的ByteArrayContent集合
/// </summary>
/// <param name="collection"></param>
/// <returns></returns>
private List<ByteArrayContent> GetFormDataByteArrayContent(NameValueCollection collection)
{
List<ByteArrayContent> list = new List<ByteArrayContent>();
foreach (var key in collection.AllKeys)
{
var dataContent = new ByteArrayContent(Encoding.UTF8.GetBytes(collection[key]));
dataContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = key
};
list.Add(dataContent);
}
return list;
}
解决办法为StreamContent设置头,代码如下
//解决方案
streamContent.Headers.Add("Content-Type", "application/octet-stream");
String headerValue = "form-data; name=\"files[]\"; filename=\"" + info.Name + "\"";
byte[] bytes = Encoding.UTF8.GetBytes(headerValue);
headerValue = "";
foreach (byte b in bytes)
{
headerValue += (Char)b;
}
streamContent.Headers.Add("Content-Disposition", headerValue