The answer has several parts.
First, to upload the file, you can use a view with code like this:
@using (Html.BeginForm())
{
}
@section scripts
{
$(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);
});
});
});
}
Second, to receive this data, create a controller, with a method like this:
public class FileController : ApiController
{
[HttpPost]
public async Task Upload()
{
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
// extract file name and file contents
var fileNameParam = provider.Contents[0].Headers.ContentDisposition.Parameters
.FirstOrDefault(p => p.Name.ToLower() == "filename");
string fileName = (fileNameParam == null) ? "" : fileNameParam.Value.Trim('"');
byte[] file = await provider.Contents[0].ReadAsByteArrayAsync();
// Here you can use EF with an entity with a byte[] property, or
// an stored procedure with a varbinary parameter to insert the
// data into the DB
var result
= string.Format("Received '{0}' with length: {1}", fileName, file.Length);
return result;
}
}
Third, by default the maximum upload size is limited. You can overcome this limitations modifying web.config:
Add maxRequestLength="max size in bytes" in . (Or create this lement if it doesn't exist):
Add maxAllowedContentLength to element (or create this element if it doesn't exist)
These entries look like this:
NOTE: you should include this inside a element, so that this limits are only applied to the particular route where the files are uploaded, like this:
...
...
Beware to modify the root web.config, not the one in the Views folder.
Fourth, as to saving the data in the database, if you use EF, you simply need an entity 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 changes.
If you use stored procedures, create one which has a varbinary parameter, and pass the byte[] file as value.