为什么ContentDisposition的FileName添加额外的斜杠和引号+ Exception抛出?

时间:2017-05-03 09:44:59

标签: asp.net-web-api2

enter image description here

我试图通过ASP.NET WebApi2上传文件。我尝试了两个选项:第一个是将文件放在内存中。为此,我使用了一段代码,它是HttpContent类的扩展:

public static async Task<HttpPostedData> ParseMultipartAsync(this HttpContent postedContent)
        {
            var provider = await postedContent.ReadAsMultipartAsync();

            var files = new Dictionary<string, HttpPostedFile>(StringComparer.InvariantCultureIgnoreCase);
            var fields = new Dictionary<string, HttpPostedField>(StringComparer.InvariantCultureIgnoreCase);

            string[] toegestaneExtensies = { ".jpg", ".jpeg", ".gif", ".png", ".pdf", ".txt", ".xlsx" };

            foreach (var content in provider.Contents)
            {
                var fieldName = content.Headers.ContentDisposition.Name.Trim('"');

                if (!string.IsNullOrEmpty(content.Headers.ContentDisposition.FileName))
                {
                    bool geuploadBestandHeeftToegestaneExtensie = (toegestaneExtensies.Contains(Path.GetExtension(content.Headers.ContentDisposition.FileName)));

                    if ((content.Headers.ContentLength > 0) && geuploadBestandHeeftToegestaneExtensie)
                    {
                        var file = await content.ReadAsByteArrayAsync();
                        var fileName = content.Headers.ContentDisposition.FileName.Trim('"');
                        files.Add(fieldName, new HttpPostedFile(fieldName, fileName, file));
                    }
                }
                else
                {
                    if (fieldName != "submit")
                    {
                        var data = await content.ReadAsStringAsync();
                        fields.Add(fieldName, new HttpPostedField(fieldName, data));
                    }
                }
            }

            return new HttpPostedData(fields, files);
        }
    }

这会引发异常,因为FileName的格式不正确。我可以看到文件名是&#34;正常&#34;在图片中,但是在调查ContentDisposition时,FileName突然出现了&#34; \&#34; banana.jpg \&#34;&#34;。这是为什么?

我要做的第二件事就是保存到磁盘。这似乎工作,我可以将文件写入磁盘,但得到以下错误消息:

&#34;将MIME多部分正文部分写入输出流&#34; - &#34;访问被拒绝&#34;。

这只是以下代码:

public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
    public CustomMultipartFormDataStreamProvider(string path) : base(path)
    {
    }

    public override string GetLocalFileName(HttpContentHeaders headers)
    {
        return headers.ContentDisposition.FileName.Replace("\"", string.Empty);
    }
}

var streamProvider = new MultipartFormDataStreamProvider("d:/");
var t = await Request.Content.ReadAsMultipartAsync(streamProvider);

但没有拒绝访问,文件被写入,之前没有,文件具有正常的文件名。会发生什么事?

2 个答案:

答案 0 :(得分:2)

错误在这里: https://github.com/aspnet/HttpAbstractions/issues/446

解决方法是: var fileName = file.Headers.ContentDisposition.FileName.TrimStart('\"').TrimEnd('\"');

悲伤但真实

答案 1 :(得分:1)

甚至比nathfy的解决方案还干净:

var filename = file.Headers.ContentDisposition.FileName.Trim('\"');