C# HttpClient+文件流上传图片时中文名称乱码问题
问题及需求描述
HttpClient+文件流上传图片,图片名称为数字或者英文时,正常上传没有问题。但是当名称是中文时,如果名称不处理则上传失败。而且我是调用对方已有的接口,所以只能自己先处理好中文名称而不能先把名称转成UTF8或者其他编码格式在对方接收图片的时候再对图片名称进行转码。
初始版本(适用名称为非中文情况)
var streamContent = new StreamContent(new FileStream(filePath, FileMode.Open, FileAccess.Read));
if (string.IsNullOrEmpty(fileName))
{
fileName = filePath.Substring(filePath.LastIndexOf("/") + 1, filePath.Length - filePath.LastIndexOf("/") - 1);
}
content.Add(streamContent, "file", fileName);
尝试中…
var streamContent = new StreamContent(new FileStream(filePath, FileMode.Open, FileAccess.Read));
if (string.IsNullOrEmpty(fileName))
{
fileName = filePath.Substring(filePath.LastIndexOf("/") + 1, filePath.Length - filePath.LastIndexOf("/") - 1);
}
content.Add(streamContent, "file", fileName);
//此处尝试把中文名称先转UTF8编码格式,然后重新赋值ContentDisposition的FileName和FileNameStar。
//此时图片可以上传,但是名称需要接收时再次处理(不适用)
content.ElementAt(0).Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "file",
FileName = fileName,
FileNameStar = fileName
};
解决方案
var streamContent = new StreamContent(new FileStream(filePath, FileMode.Open, FileAccess.Read));
if (string.IsNullOrEmpty(fileName))
{
fileName = filePath.Substring(filePath.LastIndexOf("/") + 1, filePath.Length - filePath.LastIndexOf("/") - 1);
}
//解决方案
streamContent.Headers.Add("Content-Type", "application/octet-stream");
String headerValue = "form-data; name=\"file\"; filename=\"" + fileName + "\"";
byte[] bytes = Encoding.UTF8.GetBytes(headerValue);
headerValue = "";
foreach (byte b in bytes)
{
headerValue += (Char)b;
}
streamContent.Headers.Add("Content-Disposition", headerValue);
content.Add(streamContent, "file", fileName);
小尾巴
1、网上找到的其他解决方案,不知道是不是个人原因,都没实现效果,这个方案也是某个参考的某个博主的,本来想贴连接的,但是因为没有添加书签,找不到链接了。
2、此方案实测有效,但是当名称中包含“-”短线时好像还是有点问题,后续再继续调整。