我们正在使用MultipartFormDataStreamProvider
来保存客户端的文件上传。我强烈要求文件大小必须大于1KB。最简单的办法当然是将文件保存到磁盘然后查看文件,遗憾的是我不能这样做。将文件保存到磁盘后,我无法访问它,因此我需要在将文件保存到磁盘之前查看该文件。我一直在查看流提供商的属性,试图弄清楚文件的大小,但不幸的是我没有成功。
我使用的测试文件是1025字节。
MultipartFormDataStreamProvider.BufferSize是4096
Headers.ContentDisposition.Size为null
ContentLength为空
有没有办法在保存到文件系统之前确定文件大小?
答案 0 :(得分:3)
感谢Guanxi,我能够制定解决方案。我在链接中使用他的代码作为基础我只是添加了一点async / await goodness :)。我想添加解决方案以防万一它可以帮助其他人:
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);
}
}
}
}
}
答案 1 :(得分:1)
您也可以在不使用MultipartFormDataStreamProvider
的情况下阅读请求内容。在这种情况下,所有请求内容(包括文件)都将在内存中。我在this link给出了一个如何做到这一点的例子。
在这种情况下,您可以读取文件大小的标题或读取流并检查文件大小。如果它符合您的标准,则只将其写入所需位置。