This article shows how to upload a file in a web application with the Web API and Entity Framework using AJAX.
Step 1
Create a web API project as shown in Figure 1 and Figure 2.
Figure 1
Figure 2
Your project structure will be as shown in Figure 3.
Figure 3
Step 2
Here I have used an image file uploading to explain the process.
Right-click on the model folder and add a class. In my case I named it FileUpload.cs.
Write the following code in the FileUpload class.
- public class FileUpload {
- [Key]
- [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
- public int imageid {
- get;
- set;
- }
- public string imagename {
- get;
- set;
- }
- public byte[] imagedata {
- get;
- set;
- }
- }
Right-click on the Model folder and add one more class. In my case I named it FileUploadContext.cs.
Write the following code in the FileUploadContext class.
- public class FileUploadContext: DbContext {
- public FileUploadContext(): base("name=TestConnection") {}
- public DbSet < FileUpload > fileUpload {
- get;
- set;
- }
- }
Step 3
Open the web.confiq file to modify the connection as in the following:
- <connectionStrings>
- <add name="TestConnection" connectionString="Data Source= Your Database server name;Initial Catalog= Your Database Name;Integrated Security=True" providerName="System.Data.SqlClient" />
- </connectionStrings>
After doing that build your application once.
Step 4
It's time to add the controller class.
Right-click on the controller folder and add the controller as shown in Figure 4 and Figure 5.
Figure 4
Figure 5
Step 5
Modify the POST based on our application's needs in FileUploadsController.cs.
Replace the code in the POST: api/FileUploads region with the following code in FileUploadsController.cs:
- [HttpPost]
- public IHttpActionResult PostFileUpload() {
- if (HttpContext.Current.Request.Files.AllKeys.Any()) {
-
- var httpPostedFile = HttpContext.Current.Request.Files["UploadedImage"];
- if (httpPostedFile != null) {
- FileUpload imgupload = new FileUpload();
- int length = httpPostedFile.ContentLength;
- imgupload.imagedata = new byte[length];
- httpPostedFile.InputStream.Read(imgupload.imagedata, 0, length);
- imgupload.imagename = Path.GetFileName(httpPostedFile.FileName);
- db.fileUpload.Add(imgupload);
- db.SaveChanges();
- var fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath("~/UploadedFiles"), httpPostedFile.FileName);
-
- httpPostedFile.SaveAs(fileSavePath);
- return Ok("Image Uploaded");
- }
- }
- return Ok("Image is not Uploaded");
- }
Step 6
Create one new folder in the project named UploadedFiles to save the image.
Right-click on the project and add a HTML page.
The Design
- !DOCTYPE html>
- <html
- xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <title>File Upload Demo</title>
- <script src="Js/Upload.js"></script>
- <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
- <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
- </head>
- <body>
- <div id="example">
- <div class="demo-section k-header">
- <h3>Image Upload</h3>
- <br />
- <div>
- <label for="fileUpload">
- Select File to Upload:
-
- <input id="fileUpload" type="file" name="files" />
- <br />
- <br />
- <input id="btnUploadFile" type="button" value="Upload File" class="btn-primary" />
- </div>
- </div>
- </div>
- </div>
- </body>
- </html>
The Ajax call script
- Upload.js,
-
- $(document).ready(function() {
- $('#btnUploadFile').on('click', function() {
- var data = new FormData()
- var files = $("#fileUpload").get(0).files;
-
- if (files.length > 0) {
- data.append("UploadedImage", files[0]);
- }
-
- var ajaxRequest = $.ajax({
- type: "POST",
- url: "http://localhost:59453/api/FileUploads",
- contentType: false,
- processData: false,
- data: data
- });
- ajaxRequest.done(function(xhr, textStatus) {});
- });
- });
In the browser:
Figure 6
Check the response using the fire bug development tool, as shown in Figure 7.
Figure 7
Check your database.
Figure 8
Yes! The image details have been inserted into the table.
Check the UploadedFiles folder as in the following:
Yes! The Image is copied to the UploadedFiles folder.
That's it, enjoy coding.