我在流文件上传上使用来自.net示例的代码:
[HttpPost]
public async Task<IActionResult> Post()
{
var request = HttpContext.Request;
// validation of Content-Type
// 1. first, it must be a form-data request
// 2. a boundary should be found in the Content-Type
if (!request.HasFormContentType ||
!MediaTypeHeaderValue.TryParse(request.ContentType, out var mediaTypeHeader) ||
string.IsNullOrEmpty(mediaTypeHeader.Boundary.Value))
{
return new UnsupportedMediaTypeResult();
}
var reader = new MultipartReader(mediaTypeHeader.Boundary.Value, request.Body);
var section = await reader.ReadNextSectionAsync();
// This sample try to get the first file from request and save it
// Make changes according to your needs in actual use
while (section != null)
{
var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition,
out var contentDisposition);
if (hasContentDispositionHeader && contentDisposition.DispositionType.Equals("form-data") &&
!string.IsNullOrEmpty(contentDisposition.FileName.Value))
{
await _uploader.UploadAsync(section.Body);
return Ok();
}
section = await reader.ReadNextSectionAsync();
}
// If the code runs to this location, it means that no files have been saved
return BadRequest("No files data in the request.");
}但问题是,我能够上传一个20 is的PDF。我想把这个减到5MB。理想情况下,我希望能够设置每个文件扩展名。
我读过的文档建议在我的启动中添加以下内容:
var tenMB = 10485760;
services.Configure<FormOptions>(options =>
{
options.MultipartBodyLengthLimit = tenMB;
});据我所知,这应该会引发无效的数据异常,但它不会。它什么也做不了。
我在这里做错什么了?我认为如果不把流读入内存,我就不能读到流的大小?
发布于 2021-10-05 10:04:32
我相信唯一的方法是在阅读溪流的时候。我通过一个缓冲区来提高性能(减少读取)和计算从TCP流移动到文件系统的字节数来实现这一点。如果它变得太大,流将停止,部分上传将从文件系统中删除。
var maxFileSizeBytes = _settings.MaxUploadSize;
long totalBytesRead = 0;
while (true)
{
byte[] buffer = new byte[Kilobytes.Eight];
int bytesRead = await inputStream.ReadAsync(buffer, 0, buffer.Length);
if (bytesRead == 0)
break;
totalBytesRead += bytesRead;
if (totalBytesRead > maxFileSizeBytes)
{
DeleteFile(fileName, outputStream);
throw UploadRejectedException.FileTooLarge(maxFileSizeBytes);
}
await outputStream.WriteAsync(buffer, 0, bytesRead);
}https://stackoverflow.com/questions/69412578
复制相似问题