You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: aspnetcore/blazor/file-uploads.md
+42Lines changed: 42 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -142,6 +142,48 @@ The maximum supported file size for the <xref:Microsoft.AspNetCore.Components.Fo
142
142
143
143
:::moniker-end
144
144
145
+
## Security considerations
146
+
147
+
### Avoid `IBrowserFile.Size` for file size limits
148
+
149
+
Avoid using <xref:Microsoft.AspNetCore.Components.Forms.IBrowserFile.Size?displayProperty=nameWithType> to impose a limit on the file size.
150
+
151
+
<spanaria-hidden="true">❌</span> The following approach is ***insecure*** and must be avoided:
152
+
153
+
```diff
154
+
- var fileContent = new StreamContent(file.OpenReadStream(file.Size));
155
+
```
156
+
157
+
Instead of using the unsafe client-supplied file size, explicitly specify the maximum file size. The following example sets the maximum file size (`maxFileSize`) to 15 K:
Never use a client-supplied file name for saving a file to physical storage. Create a safe file name for the file using <xref:System.IO.Path.GetRandomFileName?displayProperty=nameWithType> or <xref:System.IO.Path.GetTempFileName?displayProperty=nameWithType> to create a full path (including the file name) for temporary storage.
170
+
171
+
Razor automatically HTML encodes property values for display. The following code is safe to use:
172
+
173
+
```cshtml
174
+
@foreach (var file in Model.DatabaseFiles) {
175
+
<tr>
176
+
<td>
177
+
@file.UntrustedName
178
+
</td>
179
+
</tr>
180
+
}
181
+
```
182
+
183
+
Outside of Razor, always use <xref:System.Net.WebUtility.HtmlEncode%2A> to safely encode file names from a user's request.
184
+
185
+
Many implementations must include a check that the file exists; otherwise, the file is overwritten by a file of the same name. Supply additional logic to meet your app's specifications.
186
+
145
187
## Examples
146
188
147
189
The following examples demonstrate multiple file upload in a component. <xref:Microsoft.AspNetCore.Components.Forms.InputFileChangeEventArgs.GetMultipleFiles%2A?displayProperty=nameWithType> allows reading multiple files. Specify the maximum number of files to prevent a malicious user from uploading a larger number of files than the app expects. <xref:Microsoft.AspNetCore.Components.Forms.InputFileChangeEventArgs.File?displayProperty=nameWithType> allows reading the first and only file if the file upload doesn't support multiple files.
0 commit comments