ContentDisposition非ascii字符中的双重编码文件名

时间:2014-02-10 09:41:57

标签: c# encoding http-headers content-disposition httppostedfile

我的Content-Disposition中的文件名存在mime / quoted-printable编码问题,但HttpContext.Current.Request.Files没有解码该值,而是我得到'filenames',如:

  

=?UTF-8 2 B 4 Zm9vIOKAkyBiYXIubXNn?=

应该说“foo - bar.msg”

Wirehark捕获的Content-Disposition是:

  

形式数据;名称= \ “文件\”;文件名= \ “????= UTF-8乙Zm9vIOKAkyBiYXIubXNn = \”

我的客户代码:

string address = "http://localhost/test";
string filename = "foo – bar.msg";
Stream stream = File.Open(filename, FileMode.Open);

using (HttpClient client = new HttpClient())
{
    // Create a stream content for the file
    using (MultipartFormDataContent content = new MultipartFormDataContent())
    {
        var fileContent = new StreamContent(stream);
        fileContent.Headers.ContentDisposition = 
            new ContentDispositionHeaderValue("form-data")
        {
            Name = "\"file\"",
            FileName = filename
        };
        fileContent.Headers.ContentType = 
            new MediaTypeHeaderValue("application/octet-stream");

        content.Add(fileContent);

        Uri requestAddress = new Uri(address);

        // Post the MIME multipart form data upload with the file
        HttpResponseMessage response = 
            client.PostAsync(requestAddress, content).Result;
    }
}

我的服务器代码

public void Post()
{
    // this line results in filename being set to the encoded value
    string filename = HttpContext.Current.Request.Files[0].FileName;
}

有没有办法让HttpFileCollection解码值?或者更有可能的是,有没有办法阻止我的客户端代码对值进行双重编码?

因为内容处置位于多部分边界部分,所以我不能使用Request.Content.Headers.ContentDisposition,因为它是null?有没有办法从多部分表单数据请求的主体中获取ContentDispositionHeaderValue的实例?

1 个答案:

答案 0 :(得分:0)

当我尝试从带有特殊字符的文件中获取FileName时遇到同样的问题,在我的情况下使用重音符号。

我的解决方案是在服务器端:

  1. 删除此零件 =?utf-8?B? Zm9vIOKAkyBiYXIubXNn ?=
  2. 结果Zm9vIOKAkyBiYXIubXNn是base64字符串,使用Convert.FromBase64String获得一个字节[]-> var myBytes = Convert.FromBase64String("Zm9vIOKAkyBiYXIubXNn");
  3. 将字节解码为UTF8字符串:string utf8String = Encoding.UTF8.GetString(myBytes);,您将获得原始文件名
  4. 可选:从结果字符串中删除变音符号

PD:

Esto sirve para obtener httpPostedFile.FileName de archivos con nombre con carereres especiales o acentos。

致谢!

相关问题