I am quite new to Telerik Html Kendo. My aim is to upload a file first. Then, invoke the corresponding action method in 'Administration' controller through ajax that should take the uploaded file and other parameters on clicking the 'Submit' button as shown in image below.
Most of Telerik examples show asynchronous upload feature which invokes controller method to upload file. I don't want to do this way.
However, I have tried to upload file with onSelect event of kendo upload. It shows that file gets included however it doesn't upload.
As a result, I am unable to see any info. about uploaded file in onSuccess and onComplete event. I used formData on 'Submit' button click. However I receive null at the action method all time.
Any correct way of doing this?
Here is my html code for file upload:
<div class="well well-sm" style="width:inherit;text-align: center;float:left;">
<!--form method="post"-->
<!--div class="demo-section k-content">
<input name="files" id="files" type="file" value="Upload a Data File"/>
</div-->
<!--/form-->
@(Html.Kendo().Upload()
.Name("files")
.Multiple(false)
.Messages(m => m.Select("Please upload a Data File"))
.HtmlAttributes(new { aria_label = "file" })
.Events(events => events
.Complete("onComplete")
.Select("onSelect")
.Success("onSuccess")
.Upload("onUpload")
.Progress("onProgress"))
//.Async(a=>a.AutoUpload(false))
.Validation(v => v.AllowedExtensions(new string[] { ".csv", ".xls", ".xlsx", ".txt" }))
)
</div>
Here is the javascript code for all the js events I want to invoke.
<script>
var _files;
function onSelect(e) {
var files = e.files;
alert(files[0].name);
_files = files[0];
//file = files[0].name;
var acceptedFiles = [".xlsx", ".xls", ".txt", ".csv"]
var isAcceptedFormat = ($.inArray(files[0].extension, acceptedFiles)) != -1
if (!isAcceptedFormat) {
e.preventDefault();
$("#meter_addt_details").addClass("k-state-disabled");
//$("#submit_btn").addClass("k-state-disabled");
document.getElementById("submit_btn").disabled = true;
alert("Please upload correct file. Valid extensions are xls, xlsx,txt,csv");
}
else {
/* Here I tried to upload file didn't work out */
$("#meter_addt_details").removeClass("k-state-disabled");
// $("#submit_btn").removeClass("k-state-disabled");
document.getElementById("submit_btn").disabled = false;
@*
$("#files").kendoUpload({
async: {
saveUrl: '@Url.Action("ReadMeterFile","Administration")',
autoUpload: false
}
}); *@
$("#files").kendoUpload();
//$(".k-upload-selected").click();
@*var upload = $("#files").data("kendoUpload");
upload.upload(); *@
}
}
@*
function onUpload(e) {
$(".k-upload-selected").trigger('click');
//console.log("Upload :: " + getFileInfo(e));
}
function onSuccess(e) {
console.log(files[0].name);
_files = e.files[0];
}
function onProgress(e) {
console.log("Upload progress :: " + e.percentComplete);
}
function onComplete(e) {
console.log("Complete");
}
function onSubmitButtonClick(e) {
var formData = new FormData();
alert(_files.name);
formData.append('files', _files);
formData.append('order_num', $("#order").val());
formData.append('purchase_order', $("#purchase_order").val());
$.ajax({
url: '@Url.Action("ReadFile","Administration")',
data: formData,
type: 'POST',
processData: false,
contentType: false,
dataType: "json",
success: function (data) {
alert("Good");
}
});
}
</script>
Here is my controller:
public ActionResult ReadFile(IEnumerable<HttpPostedFileBase> files,string order_num, string purchase_order)
{
System.Diagnostics.Debug.WriteLine("File length:"+files.ToList().Capacity);
foreach(var f in files)
{
System.Diagnostics.Debug.WriteLine(f.FileName);
var fileName = Path.GetFileName(f.FileName);
var destinationPath = Path.Combine(Server.MapPath("~/App_Data"), fileName);
f.SaveAs(destinationPath);
}
//System.Diagnostics.Debug.WriteLine(file);
/*
System.Diagnostics.Debug.WriteLine("File:"+files);
System.Diagnostics.Debug.WriteLine("Order:"+order_num);
System.Diagnostics.Debug.WriteLine("Purchase Order:"+purchase_order);
return Content("");
}
Here is some code I used before for manually uploading from the kendo upload widget. From your question I think what you are looking for is the way to correctly get the info on the controller side. However, I will add the code I have used which should help you out. (My code uploads a PDF)
@(Html.Kendo().Upload()
.Name("pdf-file")
.Multiple(false)
.Validation(v => v.AllowedExtensions(new string[] { "pdf" }))
.Events(ev => ev.Select("pdfSelected"))
)
function pdfSelected(e) {
if (e.files != null && e.files.length > 0 && e.files[0] != null) {
var file = e.files[0];
if (file.validationErrors != null && file.validationErrors.length > 0) {
return; //These errors will show in the UI
}
var formData = new FormData();
formData.append('PdfFile', file.rawFile);
formData.append('AdditionalValue', 'Some String');
$.ajax({
type: 'post',
url: '[SOMEURL]',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: pdfUploaded
});
}
}
function pdfUploaded(data) {
//Whatever you want.
}
Inside of pdfSelected is the code that actually posts the file. If you want to do it all at the same time along with other properties, via a submit button. Then instead of performing the upload there. Do nothing but your validation for the upload or don't implement pdfSelected and wait until submit is clicked to perform the validation(probably better). Then on your button click
//Or course check files.length to avoid errors. Not added to keep it short
var files = $('#pdf-file').data('kendoUpload').getFiles();
var file = files[0];
Everything from "var formData = new FormData();" down, from the code above remains the same. Here is the controller code.
public ActionResult MyAction() {
string additionalValue = (string) this.Request.Form["AdditionalValue"];
HttpPostedFileBase file = this.Request.Files["PdfFile"];
//Do whatever you need to with them.
}
The file's rawFile property is what you need not just the file object because that is kendo specific.