Uploading a File With Web API and Entity Framework Using AJAX

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. 
  1. public class FileUpload {  
  2.     [Key]  
  3.     [DatabaseGenerated(DatabaseGeneratedOption.Identity)]  
  4.     public int imageid {  
  5.         get;  
  6.         set;  
  7.     }  
  8.     public string imagename {  
  9.         get;  
  10.         set;  
  11.     }  
  12.     public byte[] imagedata {  
  13.         get;  
  14.         set;  
  15.     } //this property is used to insert a  information of Image in byte format  
  16. }  
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. 
  1. public class FileUploadContext: DbContext {  
  2.     public FileUploadContext(): base("name=TestConnection") {}  
  3.     public DbSet < FileUpload > fileUpload {  
  4.         get;  
  5.         set;  
  6.     }  
  7. }  
Step 3
 
Open the web.confiq file to modify the connection as in the following:
  1. <connectionStrings>  
  2.    <add name="TestConnection" connectionString="Data Source= Your Database server name;Initial Catalog= Your Database Name;Integrated Security=True" providerName="System.Data.SqlClient" />  
  3. </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:
  1. [HttpPost]  
  2. public IHttpActionResult PostFileUpload() {  
  3.     if (HttpContext.Current.Request.Files.AllKeys.Any()) {  
  4.         // Get the uploaded image from the Files collection  
  5.         var httpPostedFile = HttpContext.Current.Request.Files["UploadedImage"];  
  6.         if (httpPostedFile != null) {  
  7.             FileUpload imgupload = new FileUpload();  
  8.             int length = httpPostedFile.ContentLength;  
  9.             imgupload.imagedata = new byte[length]; //get imagedata  
  10.             httpPostedFile.InputStream.Read(imgupload.imagedata, 0, length);  
  11.             imgupload.imagename = Path.GetFileName(httpPostedFile.FileName);  
  12.             db.fileUpload.Add(imgupload);  
  13.             db.SaveChanges();  
  14.             var fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath("~/UploadedFiles"), httpPostedFile.FileName);  
  15.             // Save the uploaded file to "UploadedFiles" folder  
  16.             httpPostedFile.SaveAs(fileSavePath);  
  17.             return Ok("Image Uploaded");  
  18.         }  
  19.     }  
  20.     return Ok("Image is not Uploaded");  
  21. }  
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
  1. !DOCTYPE html>  
  2. <html  
  3.     xmlns="http://www.w3.org/1999/xhtml">  
  4.     <head>  
  5.         <title>File Upload Demo</title>  
  6.         <script src="Js/Upload.js"></script>  
  7.         <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>  
  8.         <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">  
  9.         </head>  
  10.         <body>  
  11.             <div id="example">  
  12.                 <div class="demo-section k-header">  
  13.                     <h3>Image Upload</h3>  
  14.                     <br />  
  15.                     <div>  
  16.                         <label for="fileUpload">  
  17. Select File to Upload:   
  18.                               
  19.                             <input id="fileUpload" type="file" name="files" />  
  20.                             <br />  
  21.                             <br />  
  22.                             <input id="btnUploadFile" type="button" value="Upload File" class="btn-primary" />  
  23.                         </div>  
  24.                     </div>  
  25.                 </div>  
  26.             </div>  
  27.         </body>  
  28.     </html>  
The Ajax call script 
  1. Upload.js,  
  2.   
  3. $(document).ready(function() {  
  4.     $('#btnUploadFile').on('click', function() {  
  5.         var data = new FormData()  
  6.         var files = $("#fileUpload").get(0).files;  
  7.         // Add the uploaded image content to the form data collection  
  8.         if (files.length > 0) {  
  9.             data.append("UploadedImage", files[0]);  
  10.         }  
  11.         // Make Ajax request with the contentType = false, and procesDate = false  
  12.         var ajaxRequest = $.ajax({  
  13.             type: "POST",  
  14.             url: "http://localhost:59453/api/FileUploads",  
  15.             contentType: false,  
  16.             processData: false,  
  17.             data: data  
  18.         });  
  19.         ajaxRequest.done(function(xhr, textStatus) {});  
  20.     });  
  21. });  
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.


Similar Articles