示例#1
0
        /// <summary>
        /// ProcessFormFileAsync
        /// </summary>
        /// <param name="formFile"></param>
        /// <param name="permittedFileSuffixes"></param>
        /// <param name="sizeLimit"></param>
        /// <returns></returns>
        /// <exception cref="ApiException"></exception>
        public async Task <byte[]> ProcessFormFileAsync(IFormFile?formFile, string[] permittedFileSuffixes, long sizeLimit)
        {
            // Check the file length. This check doesn't catch files that only have
            // a BOM as their content.
            if (formFile == null || formFile.Length == 0 || permittedFileSuffixes.IsNullOrEmpty())
            {
                throw ApiExceptions.ApiUploadEmptyFile();
            }

            if (formFile.Length > sizeLimit)
            {
                throw ApiExceptions.ApiUploadOverSize();
            }

            try
            {
                using MemoryStream memoryStream = new MemoryStream();

                await formFile.CopyToAsync(memoryStream).ConfigureAwait(false);

                // Check the content length in case the file's only
                // content was a BOM and the content is actually
                // empty after removing the BOM.
                if (memoryStream.Length == 0)
                {
                    throw ApiExceptions.ApiUploadEmptyFile();
                }

                if (!IsValidFileExtensionAndSignature(
                        formFile.FileName, memoryStream, permittedFileSuffixes))
                {
                    throw ApiExceptions.ApiUploadWrongType();
                }
                else
                {
                    return(memoryStream.ToArray());
                }
            }
            catch (Exception ex)
            {
                throw ApiExceptions.ServerUnkownError(fileName: formFile.FileName, innerException: ex);
            }
        }