I am currently working on a project that requires sending intermittent status responses from a Web API method back to a jQuery AJAX call in order to display progress in the UI.
https://i.sstatic.net/Y6R4w.png
The process involves the jQuery AJAX calling the Web API method with specific parameters, initiating long-running actions. After each action completes, I aim to send a manually inputted percentage back to the AJAX call and update the UI with the progress.
Here is what I have attempted so far:
HTML:
<div class="row">
<div class="col-xs-12">
<div class="col-xs-3">
<input type="file" id="FileInput" />
</div>
<div class="col-xs-1">
<button type="button" class="btn btn-default btn-xs" id="UploadFileBtn">Upload</button>
</div>
</div>
</div>
Typescript:
instance.importFile.on('change', function () {
instance.selectedFile = this.files[0];
// This code is only for demo ... (usage of FileAPI)
console.log("name : " + instance.selectedFile.name);
console.log("size : " + instance.selectedFile.size);
console.log("type : " + instance.selectedFile.type);
console.log("date : " + instance.selectedFile.lastModifiedDate);
});
$('#UploadFileBtn').on('click', function () {
var formData = new FormData();
formData.append('file', instance.selectedFile);
$.when(FileUploadService.ProcessData(formData)).done(function () {
}).fail(function () {
}).progress(function () {
console.log("progressing...");
});
});
Web API:
public class FileUploadController : ApiController
{
[HttpPost]
public HttpResponseMessage Upload()
{
if (HttpContext.Current.Request.Files.Count > 0)
{
var postedFile = HttpContext.Current.Request.Files[0];
var fileNameParts = postedFile.FileName.Split('\\');
var fileName = fileNameParts[fileNameParts.Length - 1];
fileName = string.Format("{0}_{1}", DateTime.Now.Ticks.ToString(), fileName);
string filePath = Path.Combine("c:\\temp", fileName);
postedFile.SaveAs(filePath);
}
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StringContent("UPLOADED");
System.Threading.Thread.Sleep(5000);
return response;
}
}
Question
I have successfully created the Web API method but now I am unsure how to send intermittent responses back to the UI. I am seeking simple solutions and welcome any suggestions or examples. Thank you for your help!