I need to download list data as .xls file.My controller code is follows.
[HttpGet]
public void AttendeeListToExport()
{
string campaign_id = string.Empty;
campaign_id = ((MemberProfile)HttpContext.Current.Profile).HOWCampaignID;
AutoCRM.Services.HOW.Attendee.Manage manage = new AutoCRM.Services.HOW.Attendee.Manage();
DataSet lst = manage.AttendeeListToExport(campaign_id);
if (lst != null)
{
if (lst.Tables[0].Rows.Count > 0)
{
DataTable dt = lst.Tables[0];
// Export all the details to Excel
string filename = campaign_id + "_" + DateTime.Now.ToString("ddMMyyyy") + ".xls";
Export objExport = new Export();
objExport.ExportDetails(dt, Export.ExportFormat.Excel, filename);
}
}
}
js code
$('#exportToExcel').on("click", function () {
alert('hi');
$.ajax({
url: "/api/Attendee/AttendeeListToExport",
async: true,
cache: false,
success: function (result) {
alert(result);
}
});
});
code executing correctly but file not downloading
You can download file through javascript in following both ways :
Using HiddenIFrame :
var downloadURL = function downloadURL(url) {
var iframe;
var hiddenIFrameID = 'hiddenDownloader';
iframe = document.getElementById(hiddenIFrameID);
if (iframe === null) {
iframe = document.createElement('iframe');
iframe.id = hiddenIFrameID;
iframe.style.display = 'none';
document.body.appendChild(iframe);
}
iframe.src = url;
}
Using Jquery :
$('a').click(function(e) {
e.preventDefault(); //stop the browser from following
window.location.href = 'uploads/file.doc';
});
Download now!
If your Controller action returned a FileResult, you could download this from your javascript function like this:
$('#exportToExcel').on("click", function () {
window.open("/api/Attendee/AttendeeListToExport", "_blank");
});
You can't download files using ajax. You have to use a hidden iframe or link directly to the file.
Related
I am trying to export selected records in to a file and reload the page to update the records in a current view. I am calling web api asynchronously to get all the records. An AJAX call is executing an action in a controller successfully and returning expected data without any error but none of the 'success', 'complete' or 'error' part of ajax function is executing. There are no errors in a developer tool of the browser, no exception, nothing unusual so its getting trickier for me to investigate this issue further. Can I request your a suggestions on this please? Thanks
View :
#Html.ActionLink("Export records", "Index", null, new { Id = "myExportLinkId")
Script :
$("a#myExportLinkId").click(function (e) {
var selected = "";
$('input#myCheckBoxList').each(function () {
if (this.checked == true) {
selected += $(this).val() + ',';
}
});
if (selected != "") {
$.ajax({
url: '/MyController/MyAction',
type: 'GET',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
'MyString': 'stringValue'
},
success: function (data) {
alert("success");
},
error: function () {
alert("error");
}
});
})
And the action/method looks like this :
[HttpGet]
public async Task<ActionResult> ExportNewOrders(string OrderIdString)
{
//code to create and store file
//actually want to send the file details as json/jsonResult but for testing only returning
//string here
return Json( "Success", "application/json", JsonRequestBehavior.AllowGet);
}
Finally I have resolved this with Promisify functionality of an AJAX call. Obviously the json response I was returning had an issue so I have replaced
return Json( "Success", "application/json", JsonRequestBehavior.AllowGet);
to
return new JsonResult(){
Data = new { success = true, guid = handle, fileName = exportFileName },
ContentType = "application/json",
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
which has fixed the bug and the success function of ajax call got executed.
But other than this there were issues to wait until the file download (which involved encryption decryption, server validations etc) completes and then refresh the page. This I have resolved by implementing an ajax call with Promisify fuctionality. You can find codepen example here and the original post here.
Here is the complete code.
View/HTML
#Html.ActionLink("Export", "yourActionName", null, new { Id = "exportRequest", #onclick = "letMeKnowMyFileIsDownloaded();" })
Script/Ajax
function letMeKnowMyFileIsDownloaded() {
return new Promise(function (resolve, reject) {
$("a#exportRequest").on("click", function () {
$.ajax({
url: this.href + "?param=whatever params you want to pass",
dataType: "json",
data: {
'param1': 'value'
},
success: function (data) {
var a = document.createElement("a");
var url = '/yourControllerName/Download?fileGuid=' + data.guid + '&filename=' + data.fileName;//window.URL.createObjectURL(data);
a.href = url;
a.download = data.fileName;
document.body.append(a);
a.click();
a.remove();
window.URL.revokeObjectURL(url);
resolve(true);
},
error: function (error) {
reject(error);
}
});
});
});
}
letMeKnowMyFileIsDownloaded()
.then(function (bool) {
if (bool) {
//alert("File downloaded 👇");
window.location.reload(1);
}
})
.catch(function (error) {
alert("error");
});
I have used nuget package ClosedXML to handle excel file functionality. Using the stream to create and download the data in excel file without storing the file physically on the server.
And in the controller
//can be async or sync action
public async Task<ActionResult> Index(YourModel model)
{
//do stuff you want
var exportOrders = your_object;
//using DataTable as datasource
var dataSource = new DataTable();
//write your own function to convert your_object to your_dataSource_type
dataSource = FormatTypeToDataTable(exportOrders);
if (dataSource != null && dataSource.Rows.Count > 0)
{
//install ClosedXML.Excel from nuget
using (XLWorkbook wb = new XLWorkbook())
{
try
{
var handle = Guid.NewGuid().ToString();
wb.Worksheets.Add(dataSource, "anyNameForSheet");
string exportFileName = "yourFileName" + ".xlsx";
MemoryStream stream = GetStream(wb);
TempData[handle] = stream; exportFileName);
return new JsonResult()
{
Data = new { success = true, guid = handle, fileName = exportFileName },
ContentType = "application/json",
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
catch (Exception ex)
{
//ModelState.AddModelError("", ex.Message);
}
}
}
}
public virtual ActionResult Download(string fileGuid, string fileName)
{
if (TempData[fileGuid] != null)
{
var stream = TempData[fileGuid] as MemoryStream;
var data = stream.ToArray();
return File(data, "application/vnd.ms-excel", fileName);
}
else
{
return new EmptyResult();
}
}
I have an application where I want users to be able to upload and download their own files. I implemented the upload and download however I am concerned with XSS vulnerability of the download action. I was only able to implement the file actually downloading using GET method, but I want to secure it (usually I use POST + antiforgery token). How can I do this?
This is my controller action:
public ActionResult DownloadFile(int clientFileId)
{
var clientId = GetClientId(clientFileId);
var client = _unitOfWork.Clients.GetById(clientId);
if (client == null)
return HttpNotFound();
var file = _unitOfWork.ClientFiles.GetById(clientFileId);
if (file == null)
return HttpNotFound();
var practiceId = _unitOfWork.Users.GetPracticeIdForUser(User.Identity.GetUserId());
if (!AuthorizationHelper.CheckBelongsToPractice(_unitOfWork.Clients, typeof(Client),
practiceId, client.Id, nameof(Client.Id), nameof(Client.PracticeId)))
{
return new HttpUnauthorizedResult();
}
var fileInfo = new FileInfo(file.FilePath);
var fileName = fileInfo.Name;
if (!fileInfo.Exists)
return HttpNotFound();
var path = Path.Combine(Server.MapPath("~/ClientFiles/" + clientId + "/"), fileName);
var contentType = MimeMapping.GetMimeMapping(path);
try
{
var contentDisposition = new System.Net.Mime.ContentDisposition
{
FileName = fileName,
Inline = false,
};
Response.AppendHeader("Content-Disposition", contentDisposition.ToString());
return File(path, contentType, fileName);
}
catch (Exception ex)
{
new ExceptionlessLogger(ex).Log();
return new HttpStatusCodeResult(500);
}
}
And my ajax call
$('#client-files-table').on('click', '.js-download', function () {
var link = $(this);
$.ajax({
url: '/clients/clientfiles/downloadfile?clientFileId=' + link.attr('data-clientfile-id'),
method: 'GET',
//data: {
// __RequestVerificationToken: getToken()
//},
success: function () {
window.location = '/clients/clientfiles/downloadfile?clientFileId=' + link.attr('data-clientfile-id'),
loadPartials();
},
error: function () {
toastr.error('Unable to download.');
}
});
});
I found the answer here: https://codepen.io/chrisdpratt/pen/RKxJNo
$('#client-files-table').on('click', '.js-download', function () {
var link = $(this);
$.ajax({
url: '/clients/clientfiles/downloadfile?clientFileId=' + link.attr('data-clientfile-id'),
method: 'POST',
data: {
__RequestVerificationToken: getToken()
},
xhrFields: {
responseType: 'blob'
},
success: function (data, status, xhr) {
var a = document.createElement('a');
var url = window.URL.createObjectURL(data);
a.href = url;
var header = xhr.getResponseHeader('Content-Disposition');
var filename = getFileNameByContentDisposition(header);
a.download = filename;
a.click();
window.URL.revokeObjectURL(url);
loadPartials();
},
error: function () {
toastr.error('Unable to download.');
}
});
});
I'm trying to make use of the answer provided here:
Upload File Using WebAPI Ajax
But I keep receiving a 400 (Bad Request) error.
I've been submitting a pdf file but I keep receiving this error...
What am I doing wrong?
(FYI I'm not using MVC)
My code:
CSHTML (using Razor Syntax)
#{
Layout = "~/_SiteLayout.cshtml";
}
<label>Enter File</label>
<input type="file" name="UploadFile" id="datasheet_uploadfile" class="" accept="application/pdf"/>
<script>
$(document).ready(function() {
$('#datasheet_uploadfile').change(function() {
var data = new FormData();
var file = this.files;
data.append('file', file);
$.ajax({
url: '/api/file',
processData: false,
contentType: false,
data: data,
type: 'POST'
}).done(function(result) {
alert(result);
}).fail(function(a, b, c) {
console.log(a, b, c);
});
});
});
</script>
My WebAPI Controller
FileController.cs
public class FileController : ApiController
{
// POST api/<controller>
public HttpResponseMessage Post()
{
HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
var docfiles = new List<string>();
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
int hasheddate = DateTime.Now.GetHashCode();
//Good to use an updated name always, since many can use the same file name to upload.
string changed_name = hasheddate.ToString() + "_" + postedFile.FileName;
var filePath = HttpContext.Current.Server.MapPath("~/Content/stuff/" + changed_name);
postedFile.SaveAs(filePath); // save the file to a folder "Images" in the root of your app
changed_name = #"~\Content\stuff\" + changed_name; //store this complete path to database
docfiles.Add(changed_name);
}
result = Request.CreateResponse(HttpStatusCode.Created, docfiles);
}
else
{
result = Request.CreateResponse(HttpStatusCode.BadRequest);
}
return result;
}
}
Use the below code to upload files
$(document).ready(function () {
$('#datasheet_uploadfile').change(function () {
var data = new FormData();
data.append("file", this.files[0]);
UploadHandler.ashx.cs
public class UploadHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
try
{
string dirFullPath = HttpContext.Current.Server.MapPath("~/Uploader/");
string[] files;
int numFiles;
files = System.IO.Directory.GetFiles(dirFullPath);
numFiles = files.Length;
numFiles = numFiles + 1;
string str_image = "";
foreach (string s in context.Request.Files)
{
HttpPostedFile file = context.Request.Files[s];
string fileName = file.FileName;
string fileExtension = file.ContentType;
if (!string.IsNullOrEmpty(fileName))
{
fileExtension = Path.GetExtension(fileName);
str_image = "MyPHOTO_" + numFiles.ToString() + fileExtension;
string pathToSave_100 = HttpContext.Current.Server.MapPath("~/Uploader/") + str_image;
file.SaveAs(pathToSave_100);
}
}
// database record update logic here ()
context.Response.Write(str_image);
}
catch (Exception ac)
{
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
JsCode
/Image Upload code
function sendFile(file) {
var formData = new FormData();
formData.append('file', $('#f_UploadImage')[0].files[0]);
$.ajax({
url: 'UploadHandler.ashx',
type: 'POST',
data: formData,
cache: false,
processData: false,
contentType: false,
success: function(result) {
if (result != 'error') {
var my_path = "Uploader/" + result;
$("#myUploadedImg").attr("src", my_path);
}
},
error: function(err) {
alert(err.statusText);
}
});
}
function callImgUploader() {
var _URL = window.URL || window.webkitURL;
$("#f_UploadImage").on('change', function() {
var file, img;
if ((file = this.files[0])) {
img = new Image();
img.onload = function() {
sendFile(file);
};
img.onerror = function() {
alert("Not a valid file:" + file.type);
};
img.src = _URL.createObjectURL(file);
}
});
}
Note: My Aspx page is different folder and Image Folder and UploadHandler.ashx.cs is route folder its wrong?
after run ajax request every time its give Not-Found error how can its fixed.
Thanks.
You didn't mentioned which upload control you are using , i'm assuming it is a server side and you need to access it as follows
Change
$('#f_UploadImage')
to
$('#<%= f_UploadImage.ClientID %>')
As you said
My Aspx page is different folder and Image Folder and UploadHandler.ashx.cs
You have to change
url: 'UploadHandler.ashx',
to
url: '/UploadHandler.ashx',
Otherwise it will try to search UploadHandler.ashx in the same folder as of ajax page and give 404.
I think the problem is with the contentType try
contentType: 'multipart/form-data',
Thanks for all of your valuable feedback,
now my problem has been fixed,
problem in UploadHandler.ashx setting
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="UploadHandler.ashx.cs" Inherits="Customer.UploadHandler" %>
inherits value are not matching my UploadHandler.ashx.cs namespace that's the problem, now its fixed.
Thanks everyone.
I had a controller method to convert html to excel which worked fine when it was not a web method. But stopped working when the html string got too large. I converted it to a web method which I call via jQuery. It passes the data to the method, but no longer creates the Excel file. The code within the method has not changed. The only difference is the way I call it and the [HttpPost] decoration. The code follows:
[HttpPost]
[ValidateInput(false)]
public void ExportExcel(string aContent)
{
StringBuilder sb = new StringBuilder();
sb.Append(aContent);
Response.ClearContent();
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment; filename=ProjectData.xls");
Response.Write(sb);
Response.End();
}
And this is the jQuery stuff:
// namespace
var excel = excel || {};
$(document).ready(function () {
$('#ExcelUrl').on('click', function () {
var table = $('#tableName').val();
var content = $('#' + table).html();
excel.utilFunctions.exportToExcel(content);
});
});
excel.utilFunctions = (function ($) {
var exportToExcel = function (content) {
$.ajax({
url: "/Home/ExportExcel",
type: "POST",
data: { aContent: content }
}).done(function(data) {
alert(data);
}).fail(function(error) {
alert(error.responseText);
});
};
//public functions
return {
exportToExcel: exportToExcel
};
})(jQuery);
Any help is appreciated.
Found a solution. Apparently, since jQuery is doing the post, a file will never be generated no matter what you do.
I changed the jQuery function to create and submit a hidden form field that has my data in it.
$(document).ready(function () {
$('#ExcelUrl').on('click', function () {
var table = $('#tableName').val();
var content = $('#' + table).html().replace(/\s/g, "");
excel.utilFunctions.exportToExcel(content);
});
});
excel.utilFunctions = (function ($) {
// Excel export function
var exportToExcel = function (content) {
var form = $("<form></form>");
form.attr("method", "POST");
form.attr("action", "/Home/ExportExcel");
var dataField = $("<input/>");
dataField.attr("type", "hidden");
dataField.attr("name", "aContent");
dataField.attr("value", content);
form.append(dataField);
$(document.body).append(form);
form.submit();
};
//public functions
return {
exportToExcel: exportToExcel
};
})(jQuery);
Then I changed the ExportExcel controller function to return a FileStreamResult
public FileStreamResult ExportExcel(string aContent)
and modified the code that does the actual exporting
var byteArray = Encoding.ASCII.GetBytes(aContent);
var stream = new MemoryStream(byteArray);
return File(stream, "application/ms-excel", "FileName.xls");