Menu
-->![Upload Files For Download Upload Files For Download](/uploads/1/2/6/8/126892180/958752784.jpg)
- Upload Files Fast Download
- Upload Files For Download Google Drive
- Squarespace Upload Files For Download
- Download files from Google Drive using a computer or an Android device. Download a file. Go to drive.google.com. Click a file to download. To download multiple files, press Command (Mac) or Ctrl (Windows) while clicking other files. Right-click and click Download. Note: You can't drag a file or folder directly to your desktop. If you can't.
- Click the file you want to download to start the download process. If the download does not start you may have to right click on the size and select 'Save Target As”. These files will automatically use IPv6 if available, but you can select the IPv4 or IPv6 links to force it as required.
- FTP Command Line Tutorial for Download and upload files. How to Download and Upload Files using FTP Command Line with examples. FTP Commands LIne.
- Uploading & Downloading Files. There is a limit of 2 GB per upload session. Multiple files can be uploaded at once as long as the total size for all documents being uploaded does not exceed the 2 GB limit. Download a single or multiple files by selecting the files and/or folders you wish to download.
- Using a MemoryStream is ok if there are only small files and/or there is not much simultaneous downloads. With a large file, or a large number of simultaneous downloads the server will run out of memory because of large object heap fragmentation.
By Luke Latham, Steve Smith, and Rutger Storm
ASP.NET Core supports uploading one or more files using buffered model binding for smaller files and unbuffered streaming for larger files.
Dec 21, 2018 Any changes you make to a downloaded file appear only on your computer unless you subsequently upload the file to iCloud Drive. In iCloud Drive on iCloud.com, select the files you want to download, then click the Download button in the iCloud Drive toolbar. The files are saved in the Downloads folder on your computer (or other folder specified in your web browser’s preference.
View or download sample code (how to download)
Security considerations
Use caution when providing users with the ability to upload files to a server. Attackers may attempt to:
- Execute denial of service attacks.
- Upload viruses or malware.
- Compromise networks and servers in other ways.
Security steps that reduce the likelihood of a successful attack are:
- Upload files to a dedicated file upload area on the system, preferably to a non-system drive. Using a dedicated location makes it easier to impose security restrictions on uploaded files. Disable execute permissions on the file upload location.†
- Never persist uploaded files in the same directory tree as the app.†
- Use a safe file name determined by the app. Don't use a file name provided by the user or the untrusted file name of the uploaded file.† To display an untrusted file name in a UI or in a logging message, HTML-encode the value.
- Only allow a specific set of approved file extensions.†
- Check the file format signature to prevent a user from uploading a masqueraded file.† For example, don't permit a user to upload an .exe file with a .txt extension.
- Verify that client-side checks are also performed on the server.† Client-side checks are easy to circumvent.
- Check the size of an uploaded file and prevent uploads that are larger than expected.†
- When files shouldn't be overwritten by an uploaded file with the same name, check the file name against the database or physical storage before uploading the file.
- Run a virus/malware scanner on uploaded content before the file is stored.
†The sample app demonstrates an approach that meets the criteria.
Warning
Uploading malicious code to a system is frequently the first step to executing code that can:
- Completely gain control of a system.
- Overload a system with the result that the system crashes.
- Compromise user or system data.
- Apply graffiti to a public UI.
For information on reducing the attack surface area when accepting files from users, see the following resources:
For more information on implementing security measures, including examples from the sample app, see the Validation section.
Storage scenarios
![Upload Files For Download Upload Files For Download](/uploads/1/2/6/8/126892180/958752784.jpg)
Common storage options for files include:
- Database
- For small file uploads, a database is often faster than physical storage (file system or network share) options.
- A database is often more convenient than physical storage options because retrieval of a database record for user data can concurrently supply the file content (for example, an avatar image).
- A database is potentially less expensive than using a data storage service.
- Physical storage (file system or network share)
- For large file uploads:
- Database limits may restrict the size of the upload.
- Physical storage is often less economical than storage in a database.
- Physical storage is potentially less expensive than using a data storage service.
- The app's process must have read and write permissions to the storage location. Never grant execute permission.
- For large file uploads:
- Data storage service (for example, Azure Blob Storage)
- Services usually offer improved scalability and resiliency over on-premises solutions that are usually subject to single points of failure.
- Services are potentially lower cost in large storage infrastructure scenarios.
For more information, see Quickstart: Use .NET to create a blob in object storage. The topic demonstrates UploadFromFileAsync, but UploadFromStreamAsync can be used to save a FileStream to blob storage when working with a Stream.
File upload scenarios
Two general approaches for uploading files are buffering and streaming.
Buffering
The entire file is read into an IFormFile, which is a C# representation of the file used to process or save the file.
The resources (disk, memory) used by file uploads depend on the number and size of concurrent file uploads. If an app attempts to buffer too many uploads, the site crashes when it runs out of memory or disk space. If the size or frequency of file uploads is exhausting app resources, use streaming.
Note
Any single buffered file exceeding 64 KB is moved from memory to a temp file on disk.
Buffering small files is covered in the following sections of this topic:
Streaming
The file is received from a multipart request and directly processed or saved by the app. Streaming doesn't improve performance significantly. Streaming reduces the demands for memory or disk space when uploading files.
Streaming large files is covered in the Upload large files with streaming section.
Upload small files with buffered model binding to physical storage
To upload small files, use a multipart form or construct a POST request using JavaScript.
The following example demonstrates the use of a Razor Pages form to upload a single file (Pages/BufferedSingleFileUploadPhysical.cshtml in the sample app):
The following example is analogous to the prior example except that:
- JavaScript's (Fetch API) is used to submit the form's data.
- There's no validation.
To perform the form POST in JavaScript for clients that don't support the Fetch API, use one of the following approaches:
- Use a Fetch Polyfill (for example, window.fetch polyfill (github/fetch)).
- Use
XMLHttpRequest
. For example:
In order to support file uploads, HTML forms must specify an encoding type (
enctype
) of multipart/form-data
.For a
files
input element to support uploading multiple files provide the multiple
attribute on the <input>
element:The individual files uploaded to the server can be accessed through Model Binding using IFormFile. The sample app demonstrates multiple buffered file uploads for database and physical storage scenarios.
Warning
Don't rely on or trust the
FileName
property of IFormFile without validation. The FileName
property should only be used for display purposes and only after HTML encoding the value.The examples provided thus far don't take into account security considerations. Additional information is provided by the following sections and the sample app:
When uploading files using model binding and IFormFile, the action method can accept:
- A single IFormFile.
- Any of the following collections that represent several files:
- IEnumerable<IFormFile>
- List<IFormFile>
Note
Binding matches form files by name. For example, the HTML
name
value in <input type='file' name='formFile'>
must match the C# parameter/property bound (FormFile
). For more information, see the Match name attribute value to parameter name of POST method section.The following example:
- Loops through one or more uploaded files.
- Uses Path.GetTempFileName to return a full path for a file, including the file name.
- Saves the files to the local file system using a file name generated by the app.
- Returns the total number and size of files uploaded.
Use
Path.GetRandomFileName
to generate a file name without a path. In the following example, the path is obtained from configuration:The path passed to the FileStreammust include the file name. If the file name isn't provided, an UnauthorizedAccessException is thrown at runtime.
Files uploaded using the IFormFile technique are buffered in memory or on disk on the server before processing. Inside the action method, the IFormFile contents are accessible as a Stream. In addition to the local file system, files can be saved to a network share or to a file storage service, such as Azure Blob storage.
For another example that loops over multiple files for upload and uses safe file names, see Pages/BufferedMultipleFileUploadPhysical.cshtml.cs in the sample app.
Warning
Upload Files Fast Download
Path.GetTempFileName throws an IOException if more than 65,535 files are created without deleting previous temporary files. The limit of 65,535 files is a per-server limit. For more information on this limit on Windows OS, see the remarks in the following topics:
Upload small files with buffered model binding to a database
To store binary file data in a database using Entity Framework, define a Byte array property on the entity:
Specify a page model property for the class that includes an IFormFile:
Note
IFormFile can be used directly as an action method parameter or as a bound model property. The prior example uses a bound model property.
The
FileUpload
is used in the Razor Pages form:When the form is POSTed to the server, copy the IFormFile to a stream and save it as a byte array in the database. In the following example,
_dbContext
stores the app's database context:The preceding example is similar to a scenario demonstrated in the sample app:
- Pages/BufferedSingleFileUploadDb.cshtml
- Pages/BufferedSingleFileUploadDb.cshtml.cs
Warning
Use caution when storing binary data in relational databases, as it can adversely impact performance.
Don't rely on or trust the
FileName
property of IFormFile without validation. The FileName
property should only be used for display purposes and only after HTML encoding.The examples provided don't take into account security considerations. Additional information is provided by the following sections and the sample app:
Upload large files with streaming
The following example demonstrates how to use JavaScript to stream a file to a controller action. The file's antiforgery token is generated using a custom filter attribute and passed to the client HTTP headers instead of in the request body. Because the action method processes the uploaded data directly, form model binding is disabled by another custom filter. Within the action, the form's contents are read using a
MultipartReader
, which reads each individual MultipartSection
, processing the file or storing the contents as appropriate. After the multipart sections are read, the action performs its own model binding.The initial page response loads the form and saves an antiforgery token in a cookie (via the
GenerateAntiforgeryTokenCookieAttribute
attribute). The attribute uses ASP.NET Core's built-in antiforgery support to set a cookie with a request token:The
DisableFormValueModelBindingAttribute
is used to disable model binding:In the sample app,
GenerateAntiforgeryTokenCookieAttribute
and DisableFormValueModelBindingAttribute
are applied as filters to the page application models of /StreamedSingleFileUploadDb
and /StreamedSingleFileUploadPhysical
in Startup.ConfigureServices
using Razor Pages conventions:Since model binding doesn't read the form, parameters that are bound from the form don't bind (query, route, and header continue to work). The action method works directly with the
Request
property. A MultipartReader
is used to read each section. Key/value data is stored in a KeyValueAccumulator
. After the multipart sections are read, the contents of the KeyValueAccumulator
are used to bind the form data to a model type.The complete
StreamingController.UploadDatabase
method for streaming to a database with EF Core:The complete
StreamingController.UploadPhysical
method for streaming to a physical location:In the sample app, validation checks are handled by
FileHelpers.ProcessStreamedFile
.Validation
The sample app's
FileHelpers
class demonstrates a several checks for buffered IFormFile and streamed file uploads. For processing IFormFile buffered file uploads in the sample app, see the ProcessFormFile
method in the Utilities/FileHelpers.cs file. For processing streamed files, see the ProcessStreamedFile
method in the same file.Warning
The validation processing methods demonstrated in the sample app don't scan the content of uploaded files. In most production scenarios, a virus/malware scanner API is used on the file before making the file available to users or other systems.
Although the topic sample provides a working example of validation techniques, don't implement the
FileHelpers
class in a production app unless you:- Fully understand the implementation.
- Modify the implementation as appropriate for the app's environment and specifications.
Never indiscriminately implement security code in an app without addressing these requirements.
Content validation
Use a third party virus/malware scanning API on uploaded content.
Scanning files is demanding on server resources in high volume scenarios. If request processing performance is diminished due to file scanning, consider offloading the scanning work to a background service, possibly a service running on a server different from the app's server. Typically, uploaded files are held in a quarantined area until the background virus scanner checks them. When a file passes, the file is moved to the normal file storage location. These steps are usually performed in conjunction with a database record that indicates the scanning status of a file. By using such an approach, the app and app server remain focused on responding to requests.
File extension validation
The uploaded file's extension should be checked against a list of permitted extensions. For example:
File signature validation
A file's signature is determined by the first few bytes at the start of a file. These bytes can be used to indicate if the extension matches the content of the file. The sample app checks file signatures for a few common file types. In the following example, the file signature for a JPEG image is checked against the file:
To obtain additional file signatures, see the File Signatures Database and official file specifications.
File name security
Never use a client-supplied file name for saving a file to physical storage. Create a safe file name for the file using Path.GetRandomFileName or Path.GetTempFileName to create a full path (including the file name) for temporary storage.
Razor automatically HTML encodes property values for display. The following code is safe to use:
Outside of Razor, always HtmlEncode file name content from a user's request.
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.
Size validation
Limit the size of uploaded files.
In the sample app, the size of the file is limited to 2 MB (indicated in bytes). The limit is supplied via Configuration from the appsettings.json file:
The
FileSizeLimit
is injected into PageModel
classes:When a file size exceeds the limit, the file is rejected:
Match name attribute value to parameter name of POST method
In non-Razor forms that POST form data or use JavaScript's
FormData
directly, the name specified in the form's element or FormData
must match the name of the parameter in the controller's action.In the following example:
- When using an
<input>
element, thename
attribute is set to the valuebattlePlans
: - When using
FormData
in JavaScript, the name is set to the valuebattlePlans
:
Use a matching name for the parameter of the C# method (
battlePlans
):- For a Razor Pages page handler method named
Upload
: - For an MVC POST controller action method:
Server and app configuration
Multipart body length limit
MultipartBodyLengthLimit sets the limit for the length of each multipart body. Form sections that exceed this limit throw an InvalidDataException when parsed. The default is 134,217,728 (128 MB). Customize the limit using the MultipartBodyLengthLimit setting in
Startup.ConfigureServices
:RequestFormLimitsAttribute is used to set the MultipartBodyLengthLimit for a single page or action.
In a Razor Pages app, apply the filter with a convention in
Startup.ConfigureServices
:In a Razor Pages app or an MVC app, apply the filter to the page model or action method:
Kestrel maximum request body size
For apps hosted by Kestrel, the default maximum request body size is 30,000,000 bytes, which is approximately 28.6 MB. Customize the limit using the MaxRequestBodySize Kestrel server option:
RequestSizeLimitAttribute is used to set the MaxRequestBodySize for a single page or action.
In a Razor Pages app, apply the filter with a convention in
Startup.ConfigureServices
:Upload Files For Download Google Drive
In a Razor pages app or an MVC app, apply the filter to the page handler class or action method:
Other Kestrel limits
Other Kestrel limits may apply for apps hosted by Kestrel:
IIS content length limit
The default request limit (
maxAllowedContentLength
) is 30,000,000 bytes, which is approximately 28.6MB. Customize the limit in the web.config file:This setting only applies to IIS. The behavior doesn't occur by default when hosting on Kestrel. For more information, see Request Limits <requestLimits>.
Limitations in the ASP.NET Core Module or presence of the IIS Request Filtering Module may limit uploads to either 2 or 4 GB. For more information, see Unable to upload file greater than 2GB in size (aspnet/AspNetCore #2711).
Troubleshoot
Below are some common problems encountered when working with uploading files and their possible solutions.
Not Found error when deployed to an IIS server
The following error indicates that the uploaded file exceeds the server's configured content length:
Squarespace Upload Files For Download
For more information on increasing the limit, see the IIS content length limit section.
Connection failure
A connection error and a reset server connection probably indicates that the uploaded file exceeds Kestrel's maximum request body size. For more information, see the Kestrel maximum request body size section. Kestrel client connection limits may also require adjustment.
Null Reference Exception with IFormFile
If the controller is accepting uploaded files using IFormFile but the value is
null
, confirm that the HTML form is specifying an enctype
value of multipart/form-data
. If this attribute isn't set on the <form>
element, the file upload doesn't occur and any bound IFormFile arguments are null
. Also confirm that the upload naming in form data matches the app's naming.