file-upload - 在保存文件之前使用 MultipartFormDataStreamProvider 检测文件大小?

标签 file-upload asp.net-web-api asp.net-web-api2

我们正在使用 MultipartFormDataStreamProvider 来保存客户端上传的文件。我有一个硬性要求,即文件大小必须大于 1KB。最简单的做法当然是将文件保存到磁盘,然后不幸地查看文件,我不能这样做。将文件保存到磁盘后,我无法访问它,因此我需要在将文件保存到磁盘之前查看它。我一直在查看流提供程序的属性,试图找出文件的大小,但不幸的是我一直没有成功。

我使用的测试文件是 1025 字节。

MultipartFormDataStreamProvider.BufferSize is 4096
Headers.ContentDisposition.Size is null
ContentLength is null

有没有办法在将文件保存到文件系统之前确定文件大小?

最佳答案

感谢 Guanxi,我得以制定解决方案。我在链接中使用了他的代码作为基础,我只是添加了更多的异步/等待善良:)。我想添加解决方案以防万一它可以帮助其他人:

    private async Task SaveMultipartStreamToDisk(Guid guid, string fullPath)
    {
        var user = HttpContext.Current.User.Identity.Name;

        var multipartMemoryStreamProvider = await Request.Content.ReadAsMultipartAsync();

        foreach (var content in multipartMemoryStreamProvider.Contents)
        {
            using (content)
            {
                if (content.Headers.ContentDisposition.FileName != null)
                {
                    var existingFileName = content.Headers.ContentDisposition.FileName.Replace("\"", string.Empty);

                    Log.Information("Original File name was {OriginalFileName}: {guid} {user}", existingFileName, guid,user);

                    using (var st = await content.ReadAsStreamAsync())
                    {
                        var ext = Path.GetExtension(existingFileName.Replace("\"", string.Empty));
                        List<string> validExtensions = new List<string>() { ".pdf", ".jpg", ".jpeg", ".png" };
                        //1024 = 1KB
                        if (st.Length > 1024 && validExtensions.Contains(ext, StringComparer.OrdinalIgnoreCase))
                        {
                            var newFileName = guid + ext;
                            using (var fs = new FileStream(Path.Combine(fullPath, newFileName), FileMode.Create))
                            {
                                await st.CopyToAsync(fs);
                                Log.Information("Completed writing {file}: {guid} {user}", Path.Combine(fullPath, newFileName), guid, HttpContext.Current.User.Identity.Name);
                            }
                        }
                        else
                        {
                            if (st.Length < 1025)
                            {
                               Log.Warning("File of length {FileLength} bytes was attempted to be uploaded: {guid} {user}",st.Length,guid,user);
                            }
                            else
                            {
                                Log.Warning("A file of type {FileType} was attempted to be uploaded: {guid} {user}", ext, guid,user);
                            }
                            var responseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest)
                            {
                                Content =
                                    st.Length < 1025
                                        ? new StringContent(
                                            $"file of length {st.Length} does not meet our minumim file size requirements")
                                        : new StringContent($"a file extension of {ext} is not an acceptable type")
                            };
                            throw new HttpResponseException(responseMessage);
                        }
                    }
                }
            }
        }

关于file-upload - 在保存文件之前使用 MultipartFormDataStreamProvider 检测文件大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34318249/

相关文章:

asp.net - oauth token 共享多个应用程序

c# - Libsodium-net - 无法加载 DLL 'libsodium.dll

jquery - 在使用 jQuery 提交之前如何检查 POST 数据大小?

file-upload - 为什么我不能将上传的文件附加到电子邮件中?

c# - Microsoft.Owin.Security.Basic NuGet 包在哪里?

c# - 来自查询字符串返回请求的 Web API 可选参数缺少正文

c# - WebApi2 跨源请求被 Angular 前端阻止

asp.net-mvc - ASP.NET MVC 在子文件夹 web.config 中忽略了 maxRequestLength 和 maxAllowedContentLength 吗?

javascript - jQuery 文件上传 - 单次上传多次发送数据

asp.net-web-api - 为网站和移动应用程序混合使用 MVC 5 + WEB API 2 身份验证