This is a migrated thread and some comments may be shown as answers.

How to pass small amount of Json data back to client after uploading the file successfully?

1 Answer 480 Views
Upload
This is a migrated thread and some comments may be shown as answers.
Daochuen
Top achievements
Rank 1
Iron
Veteran
Iron
Daochuen asked on 03 Feb 2020, 03:35 PM

 

Hello,
I used Asynchronous Mode of the Upload component in my MVC project.  How to pass small amount of Json data back to client after successful uploading the file?

Thanks!

1 Answer, 1 is accepted

Sort by
1
Accepted
Veselin Tsvetanov
Telerik team
answered on 05 Feb 2020, 08:41 AM

Hi Daochuen,

Here is how to return a JSON from the controller Save action of the Upload:

public ActionResult Async_Save(IEnumerable<HttpPostedFileBase> files)
{
	// The Name of the Upload component is "files"
	if (files != null)
	{
		foreach (var file in files)
		{
			// Some browsers send file names with full path.
			// We are only interested in the file name.
			var fileName = Path.GetFileName(file.FileName);
			var physicalPath = Path.Combine(Server.MapPath("~/App_Data"), fileName);

			// The files are not actually saved in this demo
			// file.SaveAs(physicalPath);
		}
	}

	// Return an empty string to signify success
	return Json(new { message = "Message from controller" });
}

And here is how to get the JSON in the Success event handler of the Upload widget:

@(Html.Kendo().Upload()
	.Name("files")
	.Async(a => a
		.Save("Async_Save", "Home")
		.Remove("Async_Remove", "Home")
		.AutoUpload(true)
	)
	.Events(e => e.Success("onSuccess"))
)

and:

function onSuccess(e) {
	var responseText = e.XMLHttpRequest.responseText;
	var responseObject = JSON.parse(responseText);

	alert(responseObject.message);
}

Attached you will find a small sample implementing the above.

Regards,
Veselin Tsvetanov
Progress Telerik

Get quickly onboarded and successful with your Telerik UI for ASP.NET MVC with the dedicated Virtual Classroom technical training, available to all active customers.
Tags
Upload
Asked by
Daochuen
Top achievements
Rank 1
Iron
Veteran
Iron
Answers by
Veselin Tsvetanov
Telerik team
Share this question
or