// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.IO; using System.Threading; using System.Threading.Tasks; namespace Microsoft.AspNetCore.Http.Internal { public class FormFile : IFormFile { // Stream.CopyTo method uses 80KB as the default buffer size. private const int DefaultBufferSize = 80 * 1024; private readonly Stream _baseStream; private readonly long _baseStreamOffset; public FormFile(Stream baseStream, long baseStreamOffset, long length, string name, string fileName) { _baseStream = baseStream; _baseStreamOffset = baseStreamOffset; Length = length; Name = name; FileName = fileName; } /// /// Gets the raw Content-Disposition header of the uploaded file. /// public string ContentDisposition { get { return Headers["Content-Disposition"]; } set { Headers["Content-Disposition"] = value; } } /// /// Gets the raw Content-Type header of the uploaded file. /// public string ContentType { get { return Headers["Content-Type"]; } set { Headers["Content-Type"] = value; } } /// /// Gets the header dictionary of the uploaded file. /// public IHeaderDictionary Headers { get; set; } /// /// Gets the file length in bytes. /// public long Length { get; } /// /// Gets the name from the Content-Disposition header. /// public string Name { get; } /// /// Gets the file name from the Content-Disposition header. /// public string FileName { get; } /// /// Opens the request stream for reading the uploaded file. /// public Stream OpenReadStream() { return new ReferenceReadStream(_baseStream, _baseStreamOffset, Length); } /// /// Copies the contents of the uploaded file to the stream. /// /// The stream to copy the file contents to. public void CopyTo(Stream target) { if (target == null) { throw new ArgumentNullException(nameof(target)); } using (var readStream = OpenReadStream()) { readStream.CopyTo(target, DefaultBufferSize); } } /// /// Asynchronously copies the contents of the uploaded file to the stream. /// /// The stream to copy the file contents to. /// public async Task CopyToAsync(Stream target, CancellationToken cancellationToken = default(CancellationToken)) { if (target == null) { throw new ArgumentNullException(nameof(target)); } using (var readStream = OpenReadStream()) { await readStream.CopyToAsync(target, DefaultBufferSize, cancellationToken); } } } }