I have tried to download an excel file from the server to user's PC. I have the following codes from the internet. I have modified the codes a bit....
But when I run the code, nothing happens. The save dialog box is not popping up. What I really want to happen is that the excel file from the server will be saved in user's PC by popping up a save dialog box.
Please help!!!
public void DownloadFile(string url)
{
string path = Server.MapPath("~/Images/0ca66926-6977-43d3-9c97-f84a43f6ce5d.xls");
var file = new FileInfo(path);
string Outgoingfile = "FileName.xlsx";
if (file.Exists)
{
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "attachment; filename=" + Outgoingfile);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.WriteFile(file.FullName);
Response.Flush();
Response.Close();
}
else
{
Response.Write("This file does not exist.");
}
}
$.ajax({
url: '#Url.Action("DownloadFile", "Home")',
type: 'POST',
contentType: "application/json",
data: JSON.stringify({ url: urlLink}),
success: function(res) {
},
error: (function() {
alert("Error to retrieve selected report");
})
});
Since you are looking for a working download file code, I am sharing what we use.
We have two call process to download code. First call get the file prepared and saved on server. Second call shown below read file content and return a file object.
Controller.cs:
[HttpGet]
public ActionResult DownloadStream(string fileName, int searchId)
{
var tempStore = _searchService.GetTempStore(searchId);
var bytes = tempStore.DataAsBlob;
if (bytes != null)
{
var stream = new MemoryStream(bytes);
_searchService.DeleteTempStore(searchId);
return File(stream, "application/vnd.ms-excel", fileName);
}
_logger.Log("Export/DownloadStream request failed", LogCategory.Error);
return Json("Failed");
}
View.cshtml
Following line calls DownloadStream method on server, server send a file object that gets save on user machine.
window.location = '/Export/DownloadStream?fileName=' +
result+"&searchId="+searchId;
function ExportData(exportType, exportFormat) {
var searchId = document.getElementById('hfSelectedDriverId').value;
var model = { searchId: searchId, exportType: exportType, exportFormat: exportFormat };
$.ajax({
url: '#Url.Action("ExportDriverFile", "Export")',
contentType: 'application/json; charset=utf-8',
type: 'POST',
dataType: 'html',
data: JSON.stringify(model)
})
.success(function (result) {
result = result.toString().replace(/"/gi, "");
if (result == "" || result == "failed")
{
alert("File download failed. Please try again!");
}
else
{
window.location = '/Export/DownloadStream?fileName=' + result+"&searchId="+searchId;
}
})
.error(function (xhr, status) {
//alert(status);
});
}
Related
Im really struggling to get SummerNote to upload an iamge in .NET core. The trouble is the IFormFile file parameter is null when a new image is uploaded.
I initialise Summernote using the following -
$('#MessageBody').summernote({
height: ($(window).height() - 300),
callbacks: {
onImageUpload: function(image) {
uploadImage(image[0]);
}
}
});
Here is the uploadImage function -
function uploadImage(image) {
var data = new FormData();
data.append("image", image);
$.ajax({
url: '/EmailTemplate/UploadImage',
cache: false,
contentType: false,
processData: false,
data: data,
type: "post",
success: function(url) {
var image = $('<img>').attr('src', 'http://' + url);
$('#MessageBody').summernote("insertNode", image[0]);
alert(url);
var imgNode = document.createElement('img');
imgNode.src = url;
$('#MessageBody').summernote('insertNode', imgNode);
},
error: function(data) {
console.log(data);
}
});
And finally, here is the controller -
[HttpPost]
public async Task<IActionResult> UploadImage(IFormFile file)
{
string message;
var saveimg = Path.Combine(_hostingEnvironment.WebRootPath, "Images", file.FileName);
string imgext = Path.GetExtension(file.FileName);
if (imgext == ".jpg" || imgext == ".png")
{
using (var uploadimg = new FileStream(saveimg, FileMode.Create))
{
await file.CopyToAsync(uploadimg);
message = "The selected file" + file.FileName + " is saved";
}
}
else
{
message = "only JPG and PNG extensions are supported";
}
// return "filename : " + saveimg + " message :" + message;
return Content(Url.Content(saveimg));
}
The parameter is called file while the field name is image. To fix this use the same name, either file or image.
The IFormFile type represents the value of an input type=file field. IFormFile parameters are bound to fields based on their name. There may be many file fields in the same form so the type isn't enough to determine the field.
Field binding is explained in the Sources section of the Model Binding document.
I am trying to send array to the controller but it's blank in the controller parameter.
Ajax function is:
$('#pending').click(function () {
SaveTestResult("/Reception/PatientTests/SavePendingTest");
});
function SaveTestResult(url) {
var pid = $('.patientId').attr('id');
var tid = "";
var tval = "";
var tpid = "";
var tests = [];
$("table > tbody > tr").each(function () {
testId = $(this).find('.tid').val();
if (typeof (testId) != "undefined") {
tid = testId;
}
var rowText = ""
$(this).find('td').each(function () {
tpid = $(this).find('.tpId').val();
tval = $(this).find('.result').val();
if (typeof (tpid) != "undefined") {
tests.push({ PatientId: pid, TestId: tid, TestParameterId: tpid, TestValue: tval });
}
});
});
// alert(JSON.stringify(tests));
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(tests),
contentType: "application/json",
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
success: function (data) {
alert(data);
},
error: function (e) {
alert('Error' + JSON.stringify(e));
}
});
}
This is the controller method:
[HttpPost]
[Route("Reception/PatientTests/SavePendingTest")]
public async Task<IActionResult> SavePendingTest(List<PendingTestResult> pendingTestResult)
{
if (ModelState.IsValid)
{
foreach (PendingTestResult ptr in pendingTestResult)
{
_db.Add(ptr);
await _db.SaveChangesAsync();
}
// return new JsonResult("Index");
}
return new JsonResult(pendingTestResult); ;
}
But when run the code I see data array filled but inside of the SavePendingTest action, pendingTestResult is empty and not filled! I also tried the [FromBody] tag inside action params, but it does not work either!
Help me resolve this
you are sending a string with no names so the controller can not get the values.
change you code to
$.ajax({
type:"POST",
url:url,
data:test
...
});
the test should be an object not a string.
You can pass the list of objects by :
$.ajax({
type: "POST",
url: "Reception/PatientTests/SavePendingTest",
data: { pendingTestResult: tests },
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
success: function (data) {
alert(data);
},
error: function (e) {
alert('Error' + JSON.stringify(e));
}
});
pendingTestResult in data:{ pendingTestResult: tests } matches the parameter name on action and remove the contentType setting .
I can can get picture by Razor '#Action' but with Ajax Can't. I write
in controller:
public ActionResult getCommodityPic()
{
var f= File(Server.MapPath("~/App_Data/CommodityPics/eee/1") + ".jpg", "image/jpg");
return f;
}
and in java script :
$(document).ready(function () {
ShowCommodities();
getCommodityPic();
});
function getCommodityPic() {
$.ajax({
url: '#Url.action("getCommodityPic")',
type: 'Get',
dataType: 'image/jpg',
success: function (Data, Status, jqXHR) {
$('#img1').attr('src', Data);
}
});
$.ajax({
url: '#Url.Action("DownloadPic", "MyController")',
contentType: 'application/json; charset=utf-8',
datatype: 'json',
data: {
id: Id
},
type: "GET",
success: function (Data, Status, jqXHR) {
if (Data != "") {
alert("Empty");
return;
}
window.location ='#Url.Action("DonloadPic","Mycontroller")';
}
});
in Controller:
public ActionResult DownloadPic(int? id)
{
Lesson l = new Lesson();
l = db.Lesson.Single(p => p.id == id);
if (l.picture == null)
{
string targetFolder = System.Web.HttpContext.Current.Server.MapPath("~/Image/book-03.jpg");
byte[] img = System.IO.File.ReadAllBytes(targetFolder);
return File(img, "image/jpg");
}
return File(l.picture, "image/jpg");
}
If you want to display the image dynamically, then try this. You may not need an Ajax call for this.
$('#img1').html('<img src="getCommodityPic" />')
If you want to process the image (read its raw binary) then this answer should help - https://stackoverflow.com/a/20048852/6352160
I am getting error when I am trying to return result to my ajax call. Getting 500 error every time I try to return the data. Here is my ajax call:
I am getting error when I am trying to return result to my ajax call. Getting 500 error every time I try to return the data. Here is my ajax call:
$("#UserActivation").change(function () {
var userID = $("#UserActivation").val();
var searchPic;
var planID = $("#planid").val();
debugger;
$.ajax({
type: "GET",
url: "/Home/GetUserImage",
data: { userID: userID, type: 'Activation', planID: planID },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
debugger;
alert(response);
},
error: function (xhr, ajaxOptions, thrownError){
debugger;
alert(xhr.responseText);
},
complete: function (a) {
// Handle the complete event
debugger;
alert("ajax completed ");
}
});
return false;
});
And my Controller function is:
[HttpGet]
public JsonResult GetUserImage(string userID, String type, string planID)
{
if (userID != null && type != null && planID != null)
SaveUser(planID, userID, type);
DataSet ds = SQL_DB.ExecuteDataSet("SELECT * FROM [M_UserRegistration] where [ActiveFlag] = 1 and UserId='" + userID + "'");
UserData userData = new UserData();
if (ds.Tables[0].Rows.Count > 0)
{
userData.UserID = Convert.ToString(ds.Tables[0].Rows[0]["UserId"]);
userData.UserImage = "../../Images/Users/" + Convert.ToString(ds.Tables[0].Rows[0]["UserImage"]);
userData.UserName = Convert.ToString(ds.Tables[0].Rows[0]["UserFirstName"]) + " " + Convert.ToString(ds.Tables[0].Rows[0]["UserLastName"]);
}
return Json(userData);
}
Getting 500 error in the error of ajax.
You have to allow json data for request type GET like following. Hope this will solve your problem.
return Json(userData, JsonRequestBehavior.AllowGet);
I'm pretty new to MVC. I need to make ajax call to an Action with parameters using html.Action(). I'm unable to pass this..
Hope it will be helpful for other MVC begineers as well..
HTML:
<%: Html.ActionLink("Add Race", "AddRace",
new {eventId = Model.EventId, fleetId=Model.SelectedFleet.ID},
new{#onclick=string.Format("return checkFleetAddedandScroing()")}) %>
Jquery:
function checkFleetAddedandScroing() {
debugger;
$.ajax({
type: "GET",
url: '<%=Url.Action("CheckFleetExists")%>',
dataType: "json",
cache: false,
success: function (data, textStatus) {
data = eval("(" + data + ")");
if (data == true) {
return true;
}
else {
alert("Cannot Add race becasue you have not yet added any fleets and fleet scoring is checked.");
return false;
}
}, //success
error: function (req) {
}
});
}
Action:
public JsonResult CheckFleetExists(Guid fleetId )
{
bool exists = false;
try
{
exists = !db.Races.Any(r => r.FleetID == fleetId);
}
catch
{
}
return Json(exists, JsonRequestBehavior.AllowGet);
}
I need to pass fleetid to action which is in Model.SelectedFleet.ID. Its being used somewhere on pages. But i'm unable to use that somehow..
please suggest where i'm doing wrong...
It looks like you are trying to invoke a controller action using AJAX when the link is clicked and depending on the result of this call either allow the user to be redirected to the actual AddRace action or be prompted with an error message.
The problem with your code is that you are attempting to return true/false from within the success AJAX callback which doesn't make any sense. You need to always return false from the click callback and inside the success callback, depending on the returned value from the server, redirect manually using the window.location.href function.
HTML:
<%: Html.ActionLink(
"Add Race",
"AddRace",
new {
eventId = Model.EventId,
fleetId = Model.SelectedFleet.ID
},
new {
data_fleetid = Model.SelectedFleet.ID,
#class = "addRace"
}
) %>
Jquery:
<script type="text/javascript">
$(function () {
$('.addRace').click(function (evt) {
$.ajax({
type: 'GET',
url: '<%= Url.Action("CheckFleetExists") %>',
cache: false,
data: { fleetId: $(this).data('fleetid') },
success: function (data) {
if (data.exists) {
// the controller action returned true => we can redirect
// to the original url:
window.location.href = url;
}
else {
alert("Cannot Add race becasue you have not yet added any fleets and fleet scoring is checked.");
}
},
error: function (req) {
}
});
// we make sure to cancel the default action of the link
// because we will be sending an AJAX call
return false;
});
});
</script>
Action:
public ActionResult CheckFleetExists(Guid fleetId)
{
bool exists = false;
try
{
exists = !db.Races.Any(r => r.FleetID == fleetId);
}
catch
{
}
return Json(new { exists = exists }, JsonRequestBehavior.AllowGet);
}
Remark: inside your AddRace controller action don't forget to perform the same verification as you are doing inside your CheckFleetExists. The user could simply disable javascript and the AJAX call will never be done.
change your action like this :
public JsonResult CheckFleetExists(string fleetId)
{
var fleetGuid = Guid.Parse(fleetId);
bool exists = false;
try
{
exists = !db.Races.Any(r => r.FleetID == fleetGuid );
}
catch
{
}
return new JsonResult{ Data = exists};
}
and change you ActionLink so :
<%: Html.ActionLink("Add Race", "AddRace",
new {eventId = Model.EventId, fleetId=Model.SelectedFleet.ID},
new{onclick=string.Format("return checkFleetAddedandScroing({0})",Model.SelectedFleet.ID)}) %>
and your script block may look something like this :
function checkFleetAddedandScroing($fleetId) {
$.ajax({
type: "POST",
url: '<%=Url.Action("CheckFleetExists")%>',
dataType: "json",
data : { "fleetId" : $fleetId },
cache: false,
success: function (data, textStatus) {
data = eval("(" + data + ")");
if (data == true) {
return true;
}
else {
alert("Cannot Add race becasue you have not yet added any fleets and fleet scoring is checked.");
return false;
}
}, //success
error: function (req) {
}
});
}
Problem was in answers that url to action was not complete..i did it using this way
function checkFleetAddedandScroing() {
// debugger;
$.ajax({
type: "POST",
url: '<%=Url.Action("CheckFleetExists", new {eventId=Model.EventId})%>',
dataType: "json",
cache: false,
success: function (data, textStatus) {
data = eval("(" + data + ")");
if (data == true) {
return true;
}
else {
alert("Cannot Add race becasue you have not yet added any fleets and fleet scoring is checked.");
return false;
}
}, //success
error: function (req) {
}
});
}