├── .github └── FUNDING.yml ├── .gitignore ├── ClientSideApp ├── ClientSideApp.csproj ├── DemoHttpClient.cs ├── Program.cs └── test.txt ├── HttpClientMultipart.sln ├── LICENSE.md ├── README.md ├── ServerSideApp ├── Controllers │ └── FilesController.cs ├── Filters │ └── ModelBinding.cs ├── Pages │ ├── Error.cshtml │ ├── Error.cshtml.cs │ ├── Index.cshtml │ ├── Index.cshtml.cs │ ├── Shared │ │ └── _Layout.cshtml │ ├── _ViewImports.cshtml │ └── _ViewStart.cshtml ├── Program.cs ├── ServerSideApp.csproj ├── Startup.cs ├── Utilities │ ├── FileHelpers.cs │ └── MultipartRequestHelper.cs ├── appsettings.Development.json └── appsettings.json └── httpclient-file-upload-download.gif /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: changhuixu 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015/2017 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # Visual Studio 2017 auto generated files 33 | Generated\ Files/ 34 | 35 | # MSTest test Results 36 | [Tt]est[Rr]esult*/ 37 | [Bb]uild[Ll]og.* 38 | 39 | # NUNIT 40 | *.VisualState.xml 41 | TestResult.xml 42 | 43 | # Build Results of an ATL Project 44 | [Dd]ebugPS/ 45 | [Rr]eleasePS/ 46 | dlldata.c 47 | 48 | # Benchmark Results 49 | BenchmarkDotNet.Artifacts/ 50 | 51 | # .NET Core 52 | project.lock.json 53 | project.fragment.lock.json 54 | artifacts/ 55 | **/Properties/launchSettings.json 56 | 57 | # StyleCop 58 | StyleCopReport.xml 59 | 60 | # Files built by Visual Studio 61 | *_i.c 62 | *_p.c 63 | *_i.h 64 | *.ilk 65 | *.meta 66 | *.obj 67 | *.iobj 68 | *.pch 69 | *.pdb 70 | *.ipdb 71 | *.pgc 72 | *.pgd 73 | *.rsp 74 | *.sbr 75 | *.tlb 76 | *.tli 77 | *.tlh 78 | *.tmp 79 | *.tmp_proj 80 | *.log 81 | *.vspscc 82 | *.vssscc 83 | .builds 84 | *.pidb 85 | *.svclog 86 | *.scc 87 | 88 | # Chutzpah Test files 89 | _Chutzpah* 90 | 91 | # Visual C++ cache files 92 | ipch/ 93 | *.aps 94 | *.ncb 95 | *.opendb 96 | *.opensdf 97 | *.sdf 98 | *.cachefile 99 | *.VC.db 100 | *.VC.VC.opendb 101 | 102 | # Visual Studio profiler 103 | *.psess 104 | *.vsp 105 | *.vspx 106 | *.sap 107 | 108 | # Visual Studio Trace Files 109 | *.e2e 110 | 111 | # TFS 2012 Local Workspace 112 | $tf/ 113 | 114 | # Guidance Automation Toolkit 115 | *.gpState 116 | 117 | # ReSharper is a .NET coding add-in 118 | _ReSharper*/ 119 | *.[Rr]e[Ss]harper 120 | *.DotSettings.user 121 | 122 | # JustCode is a .NET coding add-in 123 | .JustCode 124 | 125 | # TeamCity is a build add-in 126 | _TeamCity* 127 | 128 | # DotCover is a Code Coverage Tool 129 | *.dotCover 130 | 131 | # AxoCover is a Code Coverage Tool 132 | .axoCover/* 133 | !.axoCover/settings.json 134 | 135 | # Visual Studio code coverage results 136 | *.coverage 137 | *.coveragexml 138 | 139 | # NCrunch 140 | _NCrunch_* 141 | .*crunch*.local.xml 142 | nCrunchTemp_* 143 | 144 | # MightyMoose 145 | *.mm.* 146 | AutoTest.Net/ 147 | 148 | # Web workbench (sass) 149 | .sass-cache/ 150 | 151 | # Installshield output folder 152 | [Ee]xpress/ 153 | 154 | # DocProject is a documentation generator add-in 155 | DocProject/buildhelp/ 156 | DocProject/Help/*.HxT 157 | DocProject/Help/*.HxC 158 | DocProject/Help/*.hhc 159 | DocProject/Help/*.hhk 160 | DocProject/Help/*.hhp 161 | DocProject/Help/Html2 162 | DocProject/Help/html 163 | 164 | # Click-Once directory 165 | publish/ 166 | 167 | # Publish Web Output 168 | *.[Pp]ublish.xml 169 | *.azurePubxml 170 | # Note: Comment the next line if you want to checkin your web deploy settings, 171 | # but database connection strings (with potential passwords) will be unencrypted 172 | *.pubxml 173 | *.publishproj 174 | 175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 176 | # checkin your Azure Web App publish settings, but sensitive information contained 177 | # in these scripts will be unencrypted 178 | PublishScripts/ 179 | 180 | # NuGet Packages 181 | *.nupkg 182 | # The packages folder can be ignored because of Package Restore 183 | **/[Pp]ackages/* 184 | # except build/, which is used as an MSBuild target. 185 | !**/[Pp]ackages/build/ 186 | # Uncomment if necessary however generally it will be regenerated when needed 187 | #!**/[Pp]ackages/repositories.config 188 | # NuGet v3's project.json files produces more ignorable files 189 | *.nuget.props 190 | *.nuget.targets 191 | 192 | # Microsoft Azure Build Output 193 | csx/ 194 | *.build.csdef 195 | 196 | # Microsoft Azure Emulator 197 | ecf/ 198 | rcf/ 199 | 200 | # Windows Store app package directories and files 201 | AppPackages/ 202 | BundleArtifacts/ 203 | Package.StoreAssociation.xml 204 | _pkginfo.txt 205 | *.appx 206 | 207 | # Visual Studio cache files 208 | # files ending in .cache can be ignored 209 | *.[Cc]ache 210 | # but keep track of directories ending in .cache 211 | !*.[Cc]ache/ 212 | 213 | # Others 214 | ClientBin/ 215 | ~$* 216 | *~ 217 | *.dbmdl 218 | *.dbproj.schemaview 219 | *.jfm 220 | *.pfx 221 | *.publishsettings 222 | orleans.codegen.cs 223 | 224 | # Including strong name files can present a security risk 225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 226 | #*.snk 227 | 228 | # Since there are multiple workflows, uncomment next line to ignore bower_components 229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 230 | #bower_components/ 231 | 232 | # RIA/Silverlight projects 233 | Generated_Code/ 234 | 235 | # Backup & report files from converting an old project file 236 | # to a newer Visual Studio version. Backup files are not needed, 237 | # because we have git ;-) 238 | _UpgradeReport_Files/ 239 | Backup*/ 240 | UpgradeLog*.XML 241 | UpgradeLog*.htm 242 | ServiceFabricBackup/ 243 | *.rptproj.bak 244 | 245 | # SQL Server files 246 | *.mdf 247 | *.ldf 248 | *.ndf 249 | 250 | # Business Intelligence projects 251 | *.rdl.data 252 | *.bim.layout 253 | *.bim_*.settings 254 | *.rptproj.rsuser 255 | 256 | # Microsoft Fakes 257 | FakesAssemblies/ 258 | 259 | # GhostDoc plugin setting file 260 | *.GhostDoc.xml 261 | 262 | # Node.js Tools for Visual Studio 263 | .ntvs_analysis.dat 264 | node_modules/ 265 | 266 | # Visual Studio 6 build log 267 | *.plg 268 | 269 | # Visual Studio 6 workspace options file 270 | *.opt 271 | 272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 273 | *.vbw 274 | 275 | # Visual Studio LightSwitch build output 276 | **/*.HTMLClient/GeneratedArtifacts 277 | **/*.DesktopClient/GeneratedArtifacts 278 | **/*.DesktopClient/ModelManifest.xml 279 | **/*.Server/GeneratedArtifacts 280 | **/*.Server/ModelManifest.xml 281 | _Pvt_Extensions 282 | 283 | # Paket dependency manager 284 | .paket/paket.exe 285 | paket-files/ 286 | 287 | # FAKE - F# Make 288 | .fake/ 289 | 290 | # JetBrains Rider 291 | .idea/ 292 | *.sln.iml 293 | 294 | # CodeRush 295 | .cr/ 296 | 297 | # Python Tools for Visual Studio (PTVS) 298 | __pycache__/ 299 | *.pyc 300 | 301 | # Cake - Uncomment if you are using it 302 | # tools/** 303 | # !tools/packages.config 304 | 305 | # Tabs Studio 306 | *.tss 307 | 308 | # Telerik's JustMock configuration file 309 | *.jmconfig 310 | 311 | # BizTalk build output 312 | *.btp.cs 313 | *.btm.cs 314 | *.odx.cs 315 | *.xsd.cs 316 | 317 | # OpenCover UI analysis results 318 | OpenCover/ 319 | 320 | # Azure Stream Analytics local run output 321 | ASALocalRun/ 322 | 323 | # MSBuild Binary and Structured Log 324 | *.binlog 325 | 326 | # NVidia Nsight GPU debugger configuration file 327 | *.nvuser 328 | 329 | # MFractors (Xamarin productivity tool) working folder 330 | .mfractor/ 331 | 332 | CSharpLabs/RunExeFromWebApi/WebApi/App_Data/ 333 | -------------------------------------------------------------------------------- /ClientSideApp/ClientSideApp.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net5.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | PreserveNewest 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /ClientSideApp/DemoHttpClient.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Net.Http; 4 | using System.Net.Http.Headers; 5 | using System.Text.Json; 6 | using System.Text.Json.Serialization; 7 | using System.Threading.Tasks; 8 | using Microsoft.Extensions.Logging; 9 | 10 | namespace ClientSideApp 11 | { 12 | public interface IDemoHttpClient 13 | { 14 | Task UploadFile(string filePath); 15 | Task DownloadFile(string guid); 16 | } 17 | 18 | public class DemoHttpClient : IDemoHttpClient 19 | { 20 | private readonly ILogger _logger; 21 | private readonly HttpClient _httpClient; 22 | private readonly string _url; 23 | 24 | public DemoHttpClient(HttpClient httpClient, ILogger logger, DemoHttpClientSettings settings) 25 | { 26 | _httpClient = httpClient; 27 | _logger = logger; 28 | _url = settings.Url; 29 | } 30 | 31 | public async Task UploadFile(string filePath) 32 | { 33 | _logger.LogInformation($"Uploading a text file [{filePath}]."); 34 | if (string.IsNullOrWhiteSpace(filePath)) 35 | { 36 | throw new ArgumentNullException(nameof(filePath)); 37 | } 38 | 39 | if (!File.Exists(filePath)) 40 | { 41 | throw new FileNotFoundException($"File [{filePath}] not found."); 42 | } 43 | using var form = new MultipartFormDataContent(); 44 | using var fileContent = new ByteArrayContent(await File.ReadAllBytesAsync(filePath)); 45 | fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data"); 46 | form.Add(fileContent, "file", Path.GetFileName(filePath)); 47 | form.Add(new StringContent("789"), "userId"); 48 | form.Add(new StringContent("some comments"), "comment"); 49 | form.Add(new StringContent("true"), "isPrimary"); 50 | 51 | var response = await _httpClient.PostAsync($"{_url}/api/files", form); 52 | response.EnsureSuccessStatusCode(); 53 | var responseContent = await response.Content.ReadAsStringAsync(); 54 | var result = JsonSerializer.Deserialize(responseContent); 55 | _logger.LogInformation("Uploading is complete."); 56 | return result?.Guid; 57 | } 58 | 59 | public async Task DownloadFile(string guid) 60 | { 61 | if (string.IsNullOrWhiteSpace(guid)) 62 | { 63 | throw new ArgumentNullException(nameof(guid), "GUID is empty."); 64 | } 65 | _logger.LogInformation($"Downloading File with GUID=[{guid}]."); 66 | var fileInfo = new FileInfo($"{guid}.txt"); 67 | 68 | var response = await _httpClient.GetAsync($"{_url}/api/files?guid={guid}"); 69 | response.EnsureSuccessStatusCode(); 70 | await using var ms = await response.Content.ReadAsStreamAsync(); 71 | await using var fs = File.Create(fileInfo.FullName); 72 | ms.Seek(0, SeekOrigin.Begin); 73 | ms.CopyTo(fs); 74 | 75 | _logger.LogInformation($"File saved as [{fileInfo.Name}]."); 76 | return fileInfo.FullName; 77 | } 78 | } 79 | 80 | public class FileUploadResult 81 | { 82 | [JsonPropertyName("guid")] 83 | public string Guid { get; set; } 84 | } 85 | 86 | public class DemoHttpClientSettings 87 | { 88 | public string Url { get; set; } 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /ClientSideApp/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading.Tasks; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using Microsoft.Extensions.Logging; 5 | 6 | namespace ClientSideApp 7 | { 8 | internal class Program 9 | { 10 | private static async Task Main(string[] args) 11 | { 12 | if (args == null || args.Length < 2) 13 | { 14 | throw new ArgumentException("Please provide file name to post"); 15 | } 16 | var services = new ServiceCollection().AddLogging(c => c.AddConsole()); 17 | services.AddSingleton(new DemoHttpClientSettings 18 | { 19 | Url = args[0] 20 | }); 21 | services.AddHttpClient(); 22 | var serviceProvider = services.BuildServiceProvider(); 23 | 24 | var client = serviceProvider.GetRequiredService(); 25 | var guid = await client.UploadFile(args[1]); 26 | await client.DownloadFile(guid); 27 | Console.WriteLine(); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /ClientSideApp/test.txt: -------------------------------------------------------------------------------- 1 | Hello World. -------------------------------------------------------------------------------- /HttpClientMultipart.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29613.14 5 | MinimumVisualStudioVersion = 15.0.26124.0 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ClientSideApp", "ClientSideApp\ClientSideApp.csproj", "{FEFD3D27-839B-405D-B6A1-BFECAE91A4D4}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ServerSideApp", "ServerSideApp\ServerSideApp.csproj", "{E2CDFF55-EF5E-4F0A-B247-73CF1C388DBE}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Debug|x64 = Debug|x64 14 | Debug|x86 = Debug|x86 15 | Release|Any CPU = Release|Any CPU 16 | Release|x64 = Release|x64 17 | Release|x86 = Release|x86 18 | EndGlobalSection 19 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 20 | {FEFD3D27-839B-405D-B6A1-BFECAE91A4D4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {FEFD3D27-839B-405D-B6A1-BFECAE91A4D4}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {FEFD3D27-839B-405D-B6A1-BFECAE91A4D4}.Debug|x64.ActiveCfg = Debug|Any CPU 23 | {FEFD3D27-839B-405D-B6A1-BFECAE91A4D4}.Debug|x64.Build.0 = Debug|Any CPU 24 | {FEFD3D27-839B-405D-B6A1-BFECAE91A4D4}.Debug|x86.ActiveCfg = Debug|Any CPU 25 | {FEFD3D27-839B-405D-B6A1-BFECAE91A4D4}.Debug|x86.Build.0 = Debug|Any CPU 26 | {FEFD3D27-839B-405D-B6A1-BFECAE91A4D4}.Release|Any CPU.ActiveCfg = Release|Any CPU 27 | {FEFD3D27-839B-405D-B6A1-BFECAE91A4D4}.Release|Any CPU.Build.0 = Release|Any CPU 28 | {FEFD3D27-839B-405D-B6A1-BFECAE91A4D4}.Release|x64.ActiveCfg = Release|Any CPU 29 | {FEFD3D27-839B-405D-B6A1-BFECAE91A4D4}.Release|x64.Build.0 = Release|Any CPU 30 | {FEFD3D27-839B-405D-B6A1-BFECAE91A4D4}.Release|x86.ActiveCfg = Release|Any CPU 31 | {FEFD3D27-839B-405D-B6A1-BFECAE91A4D4}.Release|x86.Build.0 = Release|Any CPU 32 | {E2CDFF55-EF5E-4F0A-B247-73CF1C388DBE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 33 | {E2CDFF55-EF5E-4F0A-B247-73CF1C388DBE}.Debug|Any CPU.Build.0 = Debug|Any CPU 34 | {E2CDFF55-EF5E-4F0A-B247-73CF1C388DBE}.Debug|x64.ActiveCfg = Debug|Any CPU 35 | {E2CDFF55-EF5E-4F0A-B247-73CF1C388DBE}.Debug|x64.Build.0 = Debug|Any CPU 36 | {E2CDFF55-EF5E-4F0A-B247-73CF1C388DBE}.Debug|x86.ActiveCfg = Debug|Any CPU 37 | {E2CDFF55-EF5E-4F0A-B247-73CF1C388DBE}.Debug|x86.Build.0 = Debug|Any CPU 38 | {E2CDFF55-EF5E-4F0A-B247-73CF1C388DBE}.Release|Any CPU.ActiveCfg = Release|Any CPU 39 | {E2CDFF55-EF5E-4F0A-B247-73CF1C388DBE}.Release|Any CPU.Build.0 = Release|Any CPU 40 | {E2CDFF55-EF5E-4F0A-B247-73CF1C388DBE}.Release|x64.ActiveCfg = Release|Any CPU 41 | {E2CDFF55-EF5E-4F0A-B247-73CF1C388DBE}.Release|x64.Build.0 = Release|Any CPU 42 | {E2CDFF55-EF5E-4F0A-B247-73CF1C388DBE}.Release|x86.ActiveCfg = Release|Any CPU 43 | {E2CDFF55-EF5E-4F0A-B247-73CF1C388DBE}.Release|x86.Build.0 = Release|Any CPU 44 | EndGlobalSection 45 | GlobalSection(SolutionProperties) = preSolution 46 | HideSolutionNode = FALSE 47 | EndGlobalSection 48 | GlobalSection(ExtensibilityGlobals) = postSolution 49 | SolutionGuid = {D59D7541-4D3E-40A8-82EB-879B88117D57} 50 | EndGlobalSection 51 | EndGlobal 52 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | 2 | The MIT License (MIT) 3 | 4 | Copyright (c) 2021 Changhui Xu 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy 7 | of this software and associated documentation files (the "Software"), to deal 8 | in the Software without restriction, including without limitation the rights 9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | copies of the Software, and to permit persons to whom the Software is 11 | furnished to do so, subject to the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be included in all 14 | copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | SOFTWARE. 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # HttpClient sending Multipart form-data 2 | 3 | [![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/I3I63W4OK) 4 | 5 | ## [Medium Article: Upload/Download Files Using HttpClient in C#](https://codeburst.io/upload-download-files-using-httpclient-in-c-f29051dea40c) 6 | 7 | This solution includes two projects, `ClientSideApp` and `ServerSideApp`. 8 | 9 | - The `ServerSideApp` project contains an API controller `FilesController`, which includes two actions for (1) uploading a file with Multipart form-data, and (2) downloading a file. The `ServerSideApp` project also contains a web page for uploading a file. 10 | 11 | - The `ClientSideApp` project is a Console application that uploads a `*.txt` file to the API endpoint in the `ServerSideApp`, then download the file from the `ServerSideApp`. The `ClientSideApp` project demonstrates an example of sending multipart form-data using HttpClient. 12 | 13 | The following gif image shows the screen recording of the working demo. 14 | 15 | ![httpclinet-file-upload-download](./httpclient-file-upload-download.gif) 16 | 17 | ## License 18 | 19 | Feel free to use the code in this repository as it is under MIT license. 20 | 21 | [![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/I3I63W4OK) 22 | -------------------------------------------------------------------------------- /ServerSideApp/Controllers/FilesController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Net; 6 | using System.Threading.Tasks; 7 | using Microsoft.AspNetCore.Http.Features; 8 | using Microsoft.AspNetCore.Mvc; 9 | using Microsoft.AspNetCore.WebUtilities; 10 | using Microsoft.Extensions.Configuration; 11 | using Microsoft.Extensions.Logging; 12 | using Microsoft.Net.Http.Headers; 13 | using ServerSideApp.Filters; 14 | using ServerSideApp.Utilities; 15 | 16 | namespace ServerSideApp.Controllers 17 | { 18 | [ApiController] 19 | [Route("api/[Controller]")] 20 | public class FilesController : ControllerBase 21 | { 22 | private readonly ILogger _logger; 23 | private readonly long _fileSizeLimit; 24 | private readonly string[] _permittedExtensions = { ".txt" }; 25 | private readonly string _targetFolderPath; 26 | private static readonly List MyFiles = new List(); 27 | 28 | public FilesController(ILogger logger, IConfiguration config) 29 | { 30 | _logger = logger; 31 | _fileSizeLimit = config.GetValue("FileSizeLimit"); 32 | 33 | _targetFolderPath = config.GetValue("StoredFilesPath"); // To save physical files to a path provided by configuration: 34 | //_targetFolderPath = Path.GetTempPath(); // To save physical files to the temporary files folder 35 | Directory.CreateDirectory(_targetFolderPath); 36 | } 37 | 38 | [HttpPost("")] 39 | [DisableFormValueModelBinding] 40 | public async Task Upload() 41 | { 42 | if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType)) 43 | { 44 | ModelState.AddModelError("File", "The request couldn't be processed (Error 1)."); 45 | _logger.LogWarning($"The request content type [{Request.ContentType}] is invalid."); 46 | return BadRequest(ModelState); 47 | } 48 | 49 | var formModel = new MyFormModel(); 50 | 51 | var boundary = MultipartRequestHelper.GetBoundary(MediaTypeHeaderValue.Parse(Request.ContentType), new FormOptions().MultipartBoundaryLengthLimit); 52 | var reader = new MultipartReader(boundary, HttpContext.Request.Body); 53 | var section = await reader.ReadNextSectionAsync(); 54 | 55 | while (section != null) 56 | { 57 | var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition); 58 | 59 | if (hasContentDispositionHeader) 60 | { 61 | if (contentDisposition.IsFileDisposition()) 62 | { 63 | // Don't trust the file name sent by the client. To display the file name, HTML-encode the value. 64 | var trustedFileNameForDisplay = WebUtility.HtmlEncode(contentDisposition.FileName.Value); 65 | var trustedFileNameForFileStorage = Path.GetRandomFileName(); 66 | 67 | // todo: scan the file's contents using an anti-virus/anti-malware scanner API 68 | 69 | var streamedFileContent = await FileHelpers.ProcessStreamedFile(section, contentDisposition, ModelState, _permittedExtensions, _fileSizeLimit); 70 | 71 | if (!ModelState.IsValid) 72 | { 73 | return BadRequest(ModelState); 74 | } 75 | 76 | var trustedFilePath = Path.Combine(_targetFolderPath, trustedFileNameForFileStorage); 77 | using (var targetStream = System.IO.File.Create(trustedFilePath)) 78 | { 79 | await targetStream.WriteAsync(streamedFileContent); 80 | formModel.TrustedFilePath = trustedFilePath; 81 | formModel.TrustedFileName = trustedFileNameForDisplay; 82 | _logger.LogInformation($"Uploaded file '{trustedFileNameForDisplay}' saved to '{_targetFolderPath}' as {trustedFileNameForFileStorage}"); 83 | } 84 | } 85 | else if (contentDisposition.IsFormDisposition()) 86 | { 87 | var content = new StreamReader(section.Body).ReadToEnd(); 88 | if (contentDisposition.Name == "userId" && int.TryParse(content, out var useId)) 89 | { 90 | formModel.UserId = useId; 91 | } 92 | 93 | if (contentDisposition.Name == "comment") 94 | { 95 | formModel.Comment = content; 96 | } 97 | 98 | if (contentDisposition.Name == "isPrimary" && bool.TryParse(content, out var isPrimary)) 99 | { 100 | formModel.IsPrimary = isPrimary; 101 | } 102 | } 103 | } 104 | 105 | // Drain any remaining section body that hasn't been consumed and read the headers for the next section. 106 | section = await reader.ReadNextSectionAsync(); 107 | } 108 | 109 | // todo: validate and persist formModel 110 | _logger.LogInformation(formModel.ToString()); 111 | MyFiles.Add(formModel); 112 | 113 | return Created(nameof(FilesController), formModel); 114 | } 115 | 116 | [HttpGet("")] 117 | public async Task Download([FromQuery]string guid) 118 | { 119 | var myFile = MyFiles.FirstOrDefault(x => x.Guid == guid); 120 | if (myFile == null) 121 | { 122 | _logger.LogInformation($"File with GUID={guid} Not Found."); 123 | return BadRequest($"File with GUID={guid} Not Found."); 124 | } 125 | 126 | var filePath = myFile.TrustedFilePath; 127 | _logger.LogInformation($"downloading file [{filePath}]."); 128 | var bytes = await System.IO.File.ReadAllBytesAsync(filePath); 129 | return File(bytes, GetMimeTypes(Path.GetExtension(myFile.TrustedFileName)), myFile.TrustedFileName); 130 | } 131 | 132 | private static string GetMimeTypes(string ext) 133 | { 134 | switch (ext) 135 | { 136 | case ".txt": return "text/plain"; 137 | case ".csv": return "text/csv"; 138 | case ".pdf": return "application/pdf"; 139 | case ".doc": return "application/vnd.ms-word"; 140 | case ".xls": return "application/vnd.ms-excel"; 141 | case ".ppt": return "application/vnd.ms-powerpoint"; 142 | case ".docx": return "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; 143 | case ".xlsx": return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; 144 | case ".pptx": return "application/vnd.openxmlformats-officedocument.presentationml.presentation"; 145 | case ".png": return "image/png"; 146 | case ".jpg": return "image/jpeg"; 147 | case ".jpeg": return "image/jpeg"; 148 | case ".gif": return "image/gif"; 149 | default: return "application/octet-stream"; 150 | } 151 | } 152 | } 153 | 154 | public class MyFormModel 155 | { 156 | public string TrustedFilePath { get; set; } 157 | public string TrustedFileName { get; set; } 158 | public int UserId { get; set; } 159 | public string Comment { get; set; } 160 | public string Guid { get; private set; } = System.Guid.NewGuid().ToString(); 161 | public bool IsPrimary { get; set; } 162 | 163 | public override string ToString() 164 | { 165 | return $"{nameof(TrustedFilePath)}: [{TrustedFilePath}];" + Environment.NewLine + 166 | $"{nameof(UserId)}: {UserId}; " + Environment.NewLine + 167 | $"{nameof(Guid)}: {Guid}; " + Environment.NewLine + 168 | $"{nameof(IsPrimary)}: {IsPrimary}; "; 169 | } 170 | } 171 | } 172 | -------------------------------------------------------------------------------- /ServerSideApp/Filters/ModelBinding.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.AspNetCore.Mvc.Filters; 3 | using Microsoft.AspNetCore.Mvc.ModelBinding; 4 | 5 | namespace ServerSideApp.Filters 6 | { 7 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] 8 | public class DisableFormValueModelBindingAttribute : Attribute, IResourceFilter 9 | { 10 | public void OnResourceExecuting(ResourceExecutingContext context) 11 | { 12 | var factories = context.ValueProviderFactories; 13 | factories.RemoveType(); 14 | factories.RemoveType(); 15 | factories.RemoveType(); 16 | } 17 | 18 | public void OnResourceExecuted(ResourceExecutedContext context) 19 | { 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /ServerSideApp/Pages/Error.cshtml: -------------------------------------------------------------------------------- 1 | @page 2 | @model ErrorModel 3 | @{ 4 | ViewData["Title"] = "Error"; 5 | } 6 | 7 |

Error.

8 |

An error occurred while processing your request.

9 | 10 | @if (Model.ShowRequestId) 11 | { 12 |

13 | Request ID: @Model.RequestId 14 |

15 | } 16 | 17 |

Development Mode

18 |

19 | Swapping to the Development environment displays detailed information about the error that occurred. 20 |

21 |

22 | The Development environment shouldn't be enabled for deployed applications. 23 | It can result in displaying sensitive information from exceptions to end users. 24 | For local debugging, enable the Development environment by setting the ASPNETCORE_ENVIRONMENT environment variable to Development 25 | and restarting the app. 26 |

27 | -------------------------------------------------------------------------------- /ServerSideApp/Pages/Error.cshtml.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics; 2 | using Microsoft.AspNetCore.Mvc; 3 | using Microsoft.AspNetCore.Mvc.RazorPages; 4 | 5 | namespace ServerSideApp.Pages 6 | { 7 | [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] 8 | public class ErrorModel : PageModel 9 | { 10 | public string RequestId { get; set; } 11 | 12 | public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); 13 | 14 | public void OnGet() 15 | { 16 | RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /ServerSideApp/Pages/Index.cshtml: -------------------------------------------------------------------------------- 1 | @page 2 | @model StreamedSingleFileUploadPhysicalModel 3 | @{ 4 | ViewData["Title"] = "Streamed Single File Upload with AJAX (Physical)"; 5 | } 6 | 7 |

Stream a file with AJAX to physical storage with a controller endpoint

8 | 9 |

The following form's action points to a controller endpoint that only receives the file and saves it to disk. If additional form data is added to the form, the additional data is ignored by the controller action.

10 | 11 |
13 |
14 |
15 | 16 |
17 |
18 | 19 |
20 |
21 | 22 | 23 | 24 |
25 | 26 |
27 |
28 | 29 | @section Scripts { 30 | 58 | } 59 | -------------------------------------------------------------------------------- /ServerSideApp/Pages/Index.cshtml.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc.RazorPages; 2 | 3 | namespace ServerSideApp.Pages 4 | { 5 | public class StreamedSingleFileUploadPhysicalModel : PageModel 6 | { 7 | public void OnGet() 8 | { 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /ServerSideApp/Pages/Shared/_Layout.cshtml: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | @ViewData["Title"] 7 | 8 | 9 | 10 | 11 |
12 | @RenderBody() 13 |
14 | 15 | @RenderSection("Scripts", required: false) 16 | 17 | 18 | -------------------------------------------------------------------------------- /ServerSideApp/Pages/_ViewImports.cshtml: -------------------------------------------------------------------------------- 1 | @namespace ServerSideApp.Pages 2 | @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers 3 | -------------------------------------------------------------------------------- /ServerSideApp/Pages/_ViewStart.cshtml: -------------------------------------------------------------------------------- 1 | @{ 2 | Layout = "_Layout"; 3 | } 4 | -------------------------------------------------------------------------------- /ServerSideApp/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Hosting; 6 | using Microsoft.Extensions.Configuration; 7 | using Microsoft.Extensions.Hosting; 8 | using Microsoft.Extensions.Logging; 9 | 10 | namespace ServerSideApp 11 | { 12 | public class Program 13 | { 14 | public static void Main(string[] args) 15 | { 16 | CreateHostBuilder(args).Build().Run(); 17 | } 18 | 19 | public static IHostBuilder CreateHostBuilder(string[] args) => 20 | Host.CreateDefaultBuilder(args) 21 | .ConfigureWebHostDefaults(webBuilder => 22 | { 23 | webBuilder.UseStartup(); 24 | }); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /ServerSideApp/ServerSideApp.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net5.0 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /ServerSideApp/Startup.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using Microsoft.AspNetCore.Hosting; 3 | using Microsoft.Extensions.Configuration; 4 | using Microsoft.Extensions.DependencyInjection; 5 | using Microsoft.Extensions.Hosting; 6 | using ServerSideApp.Filters; 7 | 8 | namespace ServerSideApp 9 | { 10 | public class Startup 11 | { 12 | public Startup(IConfiguration configuration) 13 | { 14 | Configuration = configuration; 15 | } 16 | 17 | public IConfiguration Configuration { get; } 18 | 19 | // This method gets called by the runtime. Use this method to add services to the container. 20 | public void ConfigureServices(IServiceCollection services) 21 | { 22 | services.AddControllers(); 23 | 24 | #region snippet_AddRazorPages 25 | services.AddRazorPages() 26 | .AddRazorPagesOptions(options => 27 | { 28 | options.Conventions 29 | .AddPageApplicationModelConvention("/Index", model => 30 | { 31 | model.Filters.Add(new DisableFormValueModelBindingAttribute()); 32 | }); 33 | }); 34 | #endregion 35 | 36 | } 37 | 38 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 39 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 40 | { 41 | if (env.IsDevelopment()) 42 | { 43 | app.UseDeveloperExceptionPage(); 44 | } 45 | 46 | app.UseRouting(); 47 | 48 | app.UseStaticFiles(); 49 | app.UseRouting(); 50 | 51 | app.UseEndpoints(endpoints => { 52 | endpoints.MapControllers(); 53 | endpoints.MapRazorPages(); 54 | }); 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /ServerSideApp/Utilities/FileHelpers.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | using Microsoft.AspNetCore.Mvc.ModelBinding; 7 | using Microsoft.AspNetCore.WebUtilities; 8 | using Microsoft.Net.Http.Headers; 9 | 10 | namespace ServerSideApp.Utilities 11 | { 12 | public static class FileHelpers 13 | { 14 | // If you require a check on specific characters in the IsValidFileExtensionAndSignature 15 | // method, supply the characters in the _allowedChars field. 16 | private static readonly byte[] AllowedChars = { }; 17 | // For more file signatures, see the File Signatures Database (https://www.filesignatures.net/) 18 | // and the official specifications for the file types you wish to add. 19 | private static readonly Dictionary> FileSignature = new Dictionary> 20 | { 21 | { ".gif", new List { new byte[] { 0x47, 0x49, 0x46, 0x38 } } }, 22 | { ".png", new List { new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A } } }, 23 | { ".jpeg", new List 24 | { 25 | new byte[] { 0xFF, 0xD8, 0xFF, 0xE0 }, 26 | new byte[] { 0xFF, 0xD8, 0xFF, 0xE2 }, 27 | new byte[] { 0xFF, 0xD8, 0xFF, 0xE3 }, 28 | } 29 | }, 30 | { ".jpg", new List 31 | { 32 | new byte[] { 0xFF, 0xD8, 0xFF, 0xE0 }, 33 | new byte[] { 0xFF, 0xD8, 0xFF, 0xE1 }, 34 | new byte[] { 0xFF, 0xD8, 0xFF, 0xE8 }, 35 | } 36 | }, 37 | { ".zip", new List 38 | { 39 | new byte[] { 0x50, 0x4B, 0x03, 0x04 }, 40 | new byte[] { 0x50, 0x4B, 0x4C, 0x49, 0x54, 0x45 }, 41 | new byte[] { 0x50, 0x4B, 0x53, 0x70, 0x58 }, 42 | new byte[] { 0x50, 0x4B, 0x05, 0x06 }, 43 | new byte[] { 0x50, 0x4B, 0x07, 0x08 }, 44 | new byte[] { 0x57, 0x69, 0x6E, 0x5A, 0x69, 0x70 }, 45 | } 46 | }, 47 | }; 48 | 49 | 50 | public static async Task ProcessStreamedFile( 51 | MultipartSection section, ContentDispositionHeaderValue contentDisposition, 52 | ModelStateDictionary modelState, string[] permittedExtensions, long sizeLimit) 53 | { 54 | try 55 | { 56 | using (var memoryStream = new MemoryStream()) 57 | { 58 | await section.Body.CopyToAsync(memoryStream); 59 | 60 | // Check if the file is empty or exceeds the size limit. 61 | if (memoryStream.Length == 0) 62 | { 63 | modelState.AddModelError("File", "The file is empty."); 64 | } 65 | else if (memoryStream.Length > sizeLimit) 66 | { 67 | var megabyteSizeLimit = sizeLimit / 1048576; 68 | modelState.AddModelError("File", $"The file exceeds {megabyteSizeLimit:N1} MB."); 69 | } 70 | else if (!IsValidFileExtensionAndSignature(contentDisposition.FileName.Value, memoryStream, permittedExtensions)) 71 | { 72 | modelState.AddModelError("File", "The file type isn't permitted or the file's signature doesn't match the file's extension."); 73 | } 74 | else 75 | { 76 | return memoryStream.ToArray(); 77 | } 78 | } 79 | } 80 | catch (Exception ex) 81 | { 82 | modelState.AddModelError("File", $"The upload failed. Please contact the Help Desk for support. Error: {ex.HResult}"); 83 | // Log the exception 84 | } 85 | 86 | return new byte[0]; 87 | } 88 | 89 | private static bool IsValidFileExtensionAndSignature(string fileName, Stream data, IEnumerable permittedExtensions) 90 | { 91 | if (string.IsNullOrEmpty(fileName) || data == null || data.Length == 0) 92 | { 93 | return false; 94 | } 95 | 96 | var ext = Path.GetExtension(fileName).ToLowerInvariant(); 97 | 98 | if (string.IsNullOrEmpty(ext) || !permittedExtensions.Contains(ext)) 99 | { 100 | return false; 101 | } 102 | 103 | data.Position = 0; 104 | 105 | using (var reader = new BinaryReader(data)) 106 | { 107 | if (ext.Equals(".txt") || ext.Equals(".csv") || ext.Equals(".prn")) 108 | { 109 | if (AllowedChars.Length == 0) 110 | { 111 | // Limits characters to ASCII encoding. 112 | for (var i = 0; i < data.Length; i++) 113 | { 114 | if (reader.ReadByte() > sbyte.MaxValue) 115 | { 116 | return false; 117 | } 118 | } 119 | } 120 | else 121 | { 122 | // Limits characters to ASCII encoding and 123 | // values of the _allowedChars array. 124 | for (var i = 0; i < data.Length; i++) 125 | { 126 | var b = reader.ReadByte(); 127 | if (b > sbyte.MaxValue || 128 | !AllowedChars.Contains(b)) 129 | { 130 | return false; 131 | } 132 | } 133 | } 134 | 135 | return true; 136 | } 137 | 138 | // Uncomment the following code block if you must permit 139 | // files whose signature isn't provided in the _fileSignature 140 | // dictionary. We recommend that you add file signatures 141 | // for files (when possible) for all file types you intend 142 | // to allow on the system and perform the file signature 143 | // check. 144 | /* 145 | if (!_fileSignature.ContainsKey(ext)) 146 | { 147 | return true; 148 | } 149 | */ 150 | 151 | // File signature check 152 | // -------------------- 153 | // With the file signatures provided in the _fileSignature 154 | // dictionary, the following code tests the input content's 155 | // file signature. 156 | var signatures = FileSignature[ext]; 157 | var headerBytes = reader.ReadBytes(signatures.Max(m => m.Length)); 158 | 159 | return signatures.Any(signature => 160 | headerBytes.Take(signature.Length).SequenceEqual(signature)); 161 | } 162 | } 163 | } 164 | } -------------------------------------------------------------------------------- /ServerSideApp/Utilities/MultipartRequestHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using Microsoft.Net.Http.Headers; 4 | 5 | namespace ServerSideApp.Utilities 6 | { 7 | public static class MultipartRequestHelper 8 | { 9 | // Content-Type: multipart/form-data; boundary="----WebKitFormBoundarymx2fSWqWSd0OxQqq" 10 | // The spec at https://tools.ietf.org/html/rfc2046#section-5.1 states that 70 characters is a reasonable limit. 11 | public static string GetBoundary(MediaTypeHeaderValue contentType, int lengthLimit) 12 | { 13 | var boundary = HeaderUtilities.RemoveQuotes(contentType.Boundary).Value; 14 | 15 | if (string.IsNullOrWhiteSpace(boundary)) 16 | { 17 | throw new InvalidDataException("Missing content-type boundary."); 18 | } 19 | 20 | if (boundary.Length > lengthLimit) 21 | { 22 | throw new InvalidDataException($"Multipart boundary length limit {lengthLimit} exceeded."); 23 | } 24 | 25 | return boundary; 26 | } 27 | 28 | public static bool IsMultipartContentType(string contentType) 29 | { 30 | return !string.IsNullOrEmpty(contentType) 31 | && contentType.IndexOf("multipart/", StringComparison.OrdinalIgnoreCase) >= 0; 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /ServerSideApp/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /ServerSideApp/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "AllowedHosts": "*", 10 | "StoredFilesPath": "c:\\temp", 11 | "FileSizeLimit": 2097152 12 | } 13 | -------------------------------------------------------------------------------- /httpclient-file-upload-download.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dotnet-labs/FileTransferUsingHttpClient/1009954e315c4da3e9a21a2f8ece408c38817406/httpclient-file-upload-download.gif --------------------------------------------------------------------------------