Javascript Callback function after download Excel - javascript

I need to send mail to user after downloading .csv file. I am not sure how to set callback function after file gets downloaded.
$.ajax({
url: '#Url.Action("GetAllCustomer", "Customers")',
type: 'POST',
data: { 'customerIds': strCustomerId },
success: function (result) {
if (result == "Success") {
location.href = '#Url.Action("DownloadFile", "Customers", new { extension = "csv"})';
} else {
toastLast = toastr.error("No data found", "Generating File");
}
}
});
In above code in first call i am getting all the customers. On success callback i am calling DownloadFile method to download csv file. i have requirement to send mail after downloading file but i am not sure how will i know that file is downloaded. Or Can I achieve with some other way.
Please find my DownloadFile method of controller as below.
public ActionResult DownloadFile(string extension)
{
var dateTime = DateTime.Now.ToString("M.dd.yy");
var fileName = dateTime + " Application File." + extension;
var array = TempData["Output"] as byte[];
if (array != null)
{
var file = File(array, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
return file;
}
else
{
return new EmptyResult();
}
}

Don't use this line
location.href = '#Url.Action("DownloadFile", "Customers", new { extension = "csv"})';
Instead use a ajax request to the Action method
$.ajax({
type: "POST",
url: '#Url.Action("DownloadFile", "Customers")',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(){
//add your sccuess handlings
}
error: function(){
//handle errors
}
});

Related

How to convert base64String to blob and send to controller via ajax in ASP.NET MVC?

I am new to ajax, currently I am using ajax trying to send base64string from view to controller and get a JsonResult as following:
$.ajax({
url: "#Url.Action("UploadSignature", "JobList")",
type: "POST",
dataType: "json",
data: { photoByte: base64String, eventRecordID: "123456" },
success: function (result) {
if (result.success === true) {
alert("Signature uploaded !");
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest);
}
});
And my controller method is as following:
[HttpPost]
public async Task<ActionResult> UploadSignature(string photoByte, string eventRecordID)
{
byte[] photoAfterConvert = Convert.FromBase64String(photoByte);
...
//Upload photoAfterConvert to server
...
return Json(new { success = true });
}
However, the code above sometimes not working especially when the base64String is too long. Once I call the ajax, it hang and never go inside the controller method. Approximately 1 minute later, it will trigger the error callback function and the message is shown as below which is meaningless.
{"readyState":0,"status":0,"statusText":"error"}
Therefore, I was thinking is there any alternative way that I can send large string data from view to controller via ajax? Is sending blob a good choice? If yes, how can I achieve it by sending blob? What is the datatype that I need to put in the controller parameter to accept blob?
Thanks in advance for any help.
try this:
function Base62ToBlob (dataURI) {
'use strict'
var byteString,
mimestring
if (dataURI.split(',')[0].indexOf('base64') !== -1) {
byteString = atob(dataURI.split(',')[1])
} else {
byteString = decodeURI(dataURI.split(',')[1])
}
mimestring = dataURI.split(',')[0].split(':')[1].split(';')[0]
var content = new Array();
for (var i = 0; i < byteString.length; i++) {
content[i] = byteString.charCodeAt(i)
}
return new Blob([new Uint8Array(content)], { type: mimestring });
}
call action metthod from client side:
function FileUploadServer (blob) {
var fd = new FormData();
fd.append("file", blob, "FileName.png");
$http.post("URL", fd, {
headers: { 'Content-Type': undefined }
})
.success(function (response, status, headers, config) {
});
}
server side call receiver method:
public ContentResult Upload()
{
var files = System.Web.HttpContext.Current.Request.Files;
return CustJson( null);
}

Copy file from local to the server nodejs

I am using nodeJS and I would like to upload a file to the server.
I have pug page where the user fill all the information and choose a file with filechooser. Then I want to send all the information on the page to the server. Therefore, I am using ajax to send a json object and given that file object can not be send through a json object I convert the File object to a json object like this:
function uploadGenome() {
var file = $(':file')[0].files[0];
var fileObject = {
'lastMod': file.lastModified,
'lastModDate': file.lastModifiedDate,
'name': file.name,
'size': file.size,
'type': file.type
};
return fileObject;
}
Then I add everything in a Json object:
var data = {};
data.file = uploadGenome();
data.name = inputs[0].value;
data.description = inputs[1].value;
data.start = inputs[3].value;
data.end = inputs[4].value;
And finally, I send everything with ajax:
$.ajax({
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json',
url: url,
success: function (data) {
console.log('success');
console.log(JSON.stringify(data));
if (data === 'done')
{
window.location.href = "/";
} else {
alert('Error Creating the Instance');
}
},
error: function () {
console.log('process error');
}
});
On the server side with NodeJS I get everything, but now how could I copy the file that I get in data.file on the server ? I mean create a copy on the project folder which is on a server.

Ask user to open or download file

I have a C# method that exports a database table and a JS function that starts a download. The JS is this:
function Export()
{
$.ajax({
cache: false,
type: "POST",
url: '#Url.Action("exportDatabaseTable", "MyController")',
data:
{
'type': "xls"
},
dataType: "text",
beforeSend: function () //Display a waiting message
{
$('#wait').show();
},
success: function (result) //Result is "Message|FilePath"
{
var res = result.split('|');
if(res[0]!="Nothing found")
window.location = "DownloadDatabaseTable?fileName=" + res[1];
alert(res[0]);
},
error: function ()
{
alert("Export failed");
},
complete: function () //Hide the waiting message
{
$('#wait').hide();
}
});
}
While the C# one, called in the success function, is this:
[HttpGet]
public ActionResult DownloadDatabaseTable(string fileName)
{
System.IO.FileInfo file = new System.IO.FileInfo(fileName);
byte[] fileBytes = System.IO.File.ReadAllBytes(fileName);
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, System.IO.Path.GetFileName(fileName));
}
Everything works, but the download starts automatically. Is there a way to show the download windows and let the user choose to download (and where to download it) or to open the file?

How to Upload Files using ajax call in asp.net?

I have created a small asp.net web forms application, to manage emails , i have created a little interface contains mandatory information to send a email, like from , to , subject etc. now i want to attach files to the email, i have used asp.net file upload controller to upload files,
and have to attach multiple files,
Now i want to send this details to code behind, so i thought the best way is to use ajax calls , because i don't want to refresh my page, but i can't figure out the way how to send the attached files to the server side,
i have read some articles and they saying i have to use FormData to send the files ,
then i have created a FormData object and appended all the attached files to the object.but how to pass this object to server side,
my js code as below,
function sendEmail() {
var data = new FormData();
var files = $('.attachment');
$.each(files, function (key, value) {
var file = $(value).data('file');
data.append(file.name, file);
});
$.ajax({
url: "OpenJobs.aspx/sendEmail",
type: "POST",
async: false,
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: null,
success: function (result) {
alert(result);
},
error: function (err) {
alert(err.statusText);
}
});
}
Any help?
You need to use Generic handler to upload files using ajax, try below code:
function sendEmail() {
var formData = new FormData();
var files = $('.attachment');
$.each(files, function (key, value) {
var file = $(value).data('file');
formData.append(file.name, file);
});
$.ajax({
url: "FileUploadHandler.ashx",
type: "POST",
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: formData,
success: function (result) {
alert(result);
},
error: function (err) {
alert(err.statusText);
}
});
}
Generic handler
<%# WebHandler Language="C#" Class="FileUploadHandler" %>
using System;
using System.Web;
public class FileUploadHandler : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
if (context.Request.Files.Count > 0)
{
HttpFileCollection files = context.Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
string fname = context.Server.MapPath("~/uploads/" + file.FileName);
file.SaveAs(fname);
}
context.Response.ContentType = "text/plain";
}
}
}

Delete a file with ajax request

I'm trying to delete a file with ajax request:
javascript:
function deleteFile(file_path)
{
var r = confirm("Sure?")
if(r == true)
{
$.ajax({
url: 'delete_file.php',
data: {'file' : file_path },
method: 'GET',
success: function (response) {
alert('Deleted!');
},
error: function () {
alert('Not Deleted!');
}
});
}
}
delete_file.php :
unlink($_GET['file']);
It returns true on succes,but the file is not deleted.
Check the response in AJAX, Best is use JSON DATA to check the response:
// Default AJAX request type is GET so no need to define
$.ajax({
url: 'delete_file.php',
data: {'file' : file_path },
dataType: 'json',
success: function (response) {
if( response.status === true ) {
alert('File Deleted!');
}
else alert('Something Went Wrong!');
}
});
Do It like this in PHP:
// First Check if file exists
$response = array('status'=>false);
if( file_exists('FILE_PATH/FILENAME') ) {
unlink('FILE_PATH/FILENAME');
$response['status'] = true;
}
// Send JSON Data to AJAX Request
echo json_encode($response);
Make sure you are giving the complete path with filename to unlink() function
Try this you need to check file, give permission, then delete it
$filename = 'full absolute file path';
if(file_exists($filename)) {
#chmod($filename, 0777);
#unlink($filename);
return true;
}
As there can be two issues either the file path is not correct or the file is not having permission.
With the above code both will be checked.

Categories

Resources