The answer consists of several parts.
First, to upload a file, you can use a view with this code:
@using (Html.BeginForm()) { <input type="file" value="Choose a file"/> <br/> <input type="button" value="Upload" id="upload"/> } @section scripts { <script type="text/javascript"> $(document).ready(function() { $('#upload').click(function () { var data = new FormData(); var file = $('form input[type=file]')[0].files[0]; data.append('file',file); $.ajax({ url: '/Api/File/Upload', processData: false, contentType: false, data: data, type: 'POST' }).done(function(result) { alert(result); }).fail(function(a, b, c) { console.log(a, b, c); }); }); }); </script> }
Secondly, to get this data, create a controller using a method similar to the following:
public class FileController : ApiController { [HttpPost] public async Task<string> Upload() { var provider = new MultipartMemoryStreamProvider(); await Request.Content.ReadAsMultipartAsync(provider);
Third, by default, the maximum download size is limited. You can overcome these limitations by changing web.config :
Add maxRequestLength="max size in bytes" to <configuration><system.web><httpRuntime> . (Or create this control if it does not exist):
Add maxAllowedContentLength to maxAllowedContentLength <configuration><system.web><security><requestFiltering><requestLimits> (or create this element if it does not exist)
These entries look like this:
<configuration> <system.web> <httpRuntime targetFramework="4.5" maxRequestLength="2000000" /> <configuration> <system.webServer> <security> <requestFiltering> <requestLimits maxAllowedContentLength="2000000000"/>
NOTE. You must include this in the <location> element so that these restrictions apply only to the specific route where the files are uploaded, for example:
<location path="Api/File/Upload"> <system.web> ... <system.webServer> ...
Beware of changing the root of web.config , not the one in the Views folder.
Fourth, as for storing data in a database, if you use EF, you just need an object like this:
public class File { public int FileId { get; set; } public string FileName { get; set; } public byte[] FileContent { get; set; } }
Create a new object of this class, add to the context and save the changes.
If you use stored procedures, create a procedure with the varbinary parameter and pass byte[] file as the value.