Upload file using WebApi, ajax
The answer has several parts.
First, to upload the file, you can use a view with code like this:
@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>
}
Second, to receive this data, create a controller, with a method like this:
public class FileController : ApiController
{
[HttpPost]
public async Task<string> 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<configuration><system.web><httpRuntime>
. (Or create this lement if it doesn't exist):Add
maxAllowedContentLength
to<configuration><system.web><security><requestFiltering><requestLimits>
element (or create this element if it doesn't exist)
These entries look like this:
<configuration>
<system.web>
<!-- kilobytes -->
<httpRuntime targetFramework="4.5" maxRequestLength="2000000" />
<configuration>
<system.webServer>
<security>
<requestFiltering>
<!-- bytes -->
<requestLimits maxAllowedContentLength="2000000000"/>
NOTE: you should include this inside a <location>
element, so that this limits are only applied to the particular route where the files are uploaded, like this:
<location path="Api/File/Upload">
<system.web>
...
<system.webServer>
...
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.
A cleaner way to do this using webAPI controller is as follows:
Create a web api controller file: UploadFileController.cs
public class UploadFileController : ApiController
{
// POST api/<controller>
public HttpResponseMessage Post()
{
HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
var docfiles = new List<string>();
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
int hasheddate = DateTime.Now.GetHashCode();
//Good to use an updated name always, since many can use the same file name to upload.
string changed_name = hasheddate.ToString() + "_" + postedFile.FileName;
var filePath = HttpContext.Current.Server.MapPath("~/Images/" + changed_name);
postedFile.SaveAs(filePath); // save the file to a folder "Images" in the root of your app
changed_name = @"~\Images\" + changed_name; //store this complete path to database
docfiles.Add(changed_name);
}
result = Request.CreateResponse(HttpStatusCode.Created, docfiles);
}
else
{
result = Request.CreateResponse(HttpStatusCode.BadRequest);
}
return result;
}
}
To use this webAPI in your markup. Use following:
<input type="hidden" id="insertPicture" />
<input id="insertFileupload" type="file" name="files[]" accept="image/*" data-url="/api/uploadfile" multiple>
<script>
$(function () {
$('#insertFileupload').fileupload({
add: function (e, data) {
var jqXHR = data.submit()
.success(function (result, textStatus, jqXHR) {/* ... */
$('#insertPicture').val(result);
alert("File Uploaded");
})
.error(function (jqXHR, textStatus, errorThrown) {/* ... */
alert(errorThrown);
})
}
});
});
You can change the type of file (extensions to accept) in the "accept" attribute of the input tag. Hope it will help! Enjoy!