Zip file not downloading using Ajax in MVC - javascript

I want to download a zip file containing .pdf files by ajax call. Here is my code. Only the zip file is not downloading, the rest are ok.
public FileResult DownloadZip(string[] Paths) {
string FilePath = string.Empty;
using (ZipFile zip = new ZipFile()) {
foreach (var item in Paths) {
string updateitem = item.Replace("'", "");
FilePath = System.Configuration.ConfigurationManager.AppSettings["ReportPath"] + updateitem;
if (System.IO.File.Exists(FilePath)) {
if (!System.IO.File.Exists(FilePath)) { continue; }
if (!zip.ContainsEntry(FilePath)) { zip.AddFile(FilePath); }
}
}
Response.Clear();
Response.AddHeader("Content-Disposition",attachmentfilename=DocumentFiles.zip");
Response.ContentType = "application/zip";
var memStream = new MemoryStream();
zip.Save(Response.OutputStream);
memStream.Position = 0;
return File(memStream, "application/zip", "DocumentFiles.zip");
}
}
$("#btnDownload").click(function () {
var reportPaths = new Array();
$('input[name="path"]:checked').each(function() {
reportPaths.push(this.value);
});
$.ajax({type: "GET",url: "/Client/CompletedCases/DownloadZip",traditional: true,data:{Paths:reportPaths},success: function (data) {},});
});

[HttpGet]
public virtual ActionResult Download(string file)
{
string fullPath = Path.Combine(Server.MapPath("~/MyFiles"), file);
return File(fullPath, "application/zip", file);
}
$.ajax({
type: 'POST',
url: '/Download', //change it accroding to your url
data: '{ "file" : "file" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (returnValue) {
window.location = '/Download?file=' + returnValue; //change accroding to you url
}
});

Related

Sending Large data from View to Controller in MVC

I am getting table records, I need to send it to Controller so that I can send email. When I tried with following code, it's throwing error
var emailList = '';
$('.checkBoxClass').each(function () {
if ($(this).is(':checked')) {
emailList += $(this).val() + ',';
}
});
body = 'Hi Team'
console.log('emIl ' + emailList);
var baseUrl = ".";
$.ajax({
type: "GET",
url: baseUrl + "/Dashboard/GetFinanceSendMail",
data: "{'emailList': '" + JSON.stringify(emailList) + "', body' : '" + body + "' }",
success: function (json) {
alert(json);
}
});
Error as : HTTP Error 404.15 - Not Found The request filtering module
is configured to deny a request where the query string is too long.
Most likely causes: Request filtering is configured on the Web server
to deny the request because the query string is too long.
I have tried to add following code, still same error
var formData = new FormData();
var objArr = [];
objArr.push({ "emIl": emailList, });
//JSON obj
formData.append('objArr', JSON.stringify(objArr))
body = 'Hi Team'
console.log('emIl ' + emailList);
var baseUrl = ".";
$.ajax({
type: "POST",
url: baseUrl + "/Dashboard/GetFinanceSendMail",
processData: false,
contentType: false,
data: formData,
Here is Controller Code
[HttpGet]
public JsonResult GetFinanceSendMail(string emailList, string body)
{
List<string> emails = emailList.Split(',').ToList();
// Send Email add optiona arg to the method
_openPobl.TriggerFinanceEmail(body, emails);
return Json(emails, JsonRequestBehavior.AllowGet);
}
fix the action, remove [get]
Route[("~/Dashboard/GetFinanceSendMail")]
public JsonResult GetFinanceSendMail(string emailList, string body)
and ajax
var emailList = '';
$('.checkBoxClass').each(function () {
if ($(this).is(':checked')) {
emailList += $(this).val() + ',';
}
});
var body = 'Hi Team';
$.ajax({
type: "POST",
url: "/Dashboard/GetFinanceSendMail",
data: {emailList: emailList, body : body },
success: function (json) {
alert(json);
}
});
but if you want to use post much more reliable to create a viewmodel class
public class ViewModel
{
public string EmailList {get;set;}
public string Body {get;set;}
}
action
Route[("~/Dashboard/GetFinanceSendMail")]
public JsonResult GetFinanceSendMail(ViewModel model)
.....
and ajax
$.ajax({
type: "POST",
url: "/Dashboard/GetFinanceSendMail",
data: { model: {emailList: emailList, body : body } },
success: function (json) {
alert(json);
}
});

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);
}

Javascript Callback function after download Excel

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
}
});

i have an error while export excel file using c# mvc

i am using asp.net mvc webapi and ajax in my project
i am calling controller using ajax and sending data with ajax
here is my ajax code
var bobj = {};
bobj.data = data;
CallAjax('post',common,'attendancesheetdownload',bobj,_getholidaylist.onsuccestendancesheetdownload, '');
function CallAjax(method, baseUrl, strUrl, strData, onSuccess, onFailure) {
callDebugger();
var dataValue = null;
var ContentType = "application/json; charset=utf-8";
strUrl = baseUrl + strUrl;
method = method.toUpperCase();
if (method == "GET") {
dataValue = strData;
}
else if (method == "POST") {
dataValue = JSON.stringify(strData);
}
callLoader(true);
$.ajax({
type: method,
url: strUrl,//users/signin
contentType: ContentType,
dataType: 'json',
data: dataValue,
async: false,
success: onSuccess,
error: function (err) {
callLoader(false);
swal({
title:err, text: "", type: "error",
showCancelButton: false, closeOnConfirm: true, confirmButtonText: "OK",
}, function (isConfirm) {
window.location = "signin";
});
//console.log(err);
}
});
}
and here is my c# controller code for excel generate
[HttpPost]
[Route("attendancesheetdownload")]
public JsonResult AttendanceSheetDownload(List<AttendanceModel> data)
{
//List<AttendanceModel> holidaylist = new List<AttendanceModel>();
try
{
System.Data.DataTable dt = new System.Data.DataTable();
using (XLWorkbook wb = new XLWorkbook())
{
//DataTable dt = new DataTable();
dt.Columns.Add("Employee Name");
dt.Columns.Add("Leaves");
// dt.Columns.Add("URL");
foreach (var item in data)
{
var row = dt.NewRow();
row["Employee Name"] = item.user_id;
row["Leaves"] = Convert.ToString(item.days);
// row["URL"] = item.URL;
dt.Rows.Add(row);
}
// dt = attendacemodel;
wb.Worksheets.Add(dt, "CusDetail");
wb.ShowRowColHeaders = false;
wb.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
wb.Style.Font.Bold = true;
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=Customers.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
return Json(data);
}
catch (Exception ex)
{
throw ex;
}
finally
{
data = null;
}
}
i dont see any error at c# side it easly pass all the step but the file is not downloading
and
when its comes to onsuccess method of ajax its give me object object error
can some one guide me how to download excel file with ajax c# and webapi

Ajax File Upload - Script Writes garbage in File

i have a Problem with my Ajax-Fileupload Script.
When I upload my Files, the Files are corrupt. When I open the File with Notepad++, i see that there are for example the following Lines:
-----------------------------22998260013704
Content-Disposition: form-data; name="0"; filename="myimage.png"
Content-Type: image/png
filecontent
-----------------------------22998260013704--
When I delete the 3 Lines bevor filecontent und the Line after filecontent, the File is ok.
I have no clue, why these 4 Lines are written to the Files.
I hope that somebody can help me.
Here is my Javascript-Code:
var myFiles = [];
function ajaxFileUpload() {
var dataid = document.getElementById("dataid").getAttribute("data-id"),
data = new FormData(),
maxSize = 100.0,
file = null,
myUrl = "xxx/save";
$.each(myFiles, function(key, value) {
console.log(key+" "+value);
file = value;
data.append(key, value);
});
var filesize = file.size;
if ((filesize/(1024*1024)) <= maxSize) {
$.ajax({
type: "PUT", //<-- http://stackoverflow.com/questions/10475313/ajax-file-upload-with-xmlhttprequest
url: myUrl,
processData: false,
contentType: false,
data: data,
beforeSend: function(xhr) {
xhr.setRequestHeader("X-File-Name", file.name);
xhr.setRequestHeader("X-File-Size", file.size);
xhr.setRequestHeader("X-myid", dataid);
},
success: function (json) {
//....
},
});
} else {
//...
}
}
And here my relevant PHP-Code:
private function copyPutFilesToTmp($directory = "") {
$temp = "xxx";
if (!is_dir($temp)) {
mkdir ($temp, 0777, true);
}
$tmpPath = $temp."/";
$filename = $_SERVER['HTTP_X_FILE_NAME'];
$in = fopen('php://input', 'r');
$ziel = $tmpPath.$filename;
if (!file_exists($ziel)) {
$fileuploadok = true;
$out = fopen($ziel, 'w');
$data = fread($in, 1024);
while($data) {
if ($data != false) {
fwrite($out, $data);
} else {
$fileuploadok = false;
}
$data = fread($in, 1024);
}
fclose($in);
fclose($out);
if ($fileuploadok === FALSE) {
//...
} else {
//...
}
} else {
//...
}
return $answer;
}
I found the problem.
if I sent the file directly as data and not within a FormData it works!
So the right Code is:
var myFiles = [];
function ajaxFileUpload() {
var dataid = document.getElementById("dataid").getAttribute("data-id"),
maxSize = 100.0,
file = null,
myUrl = "xxx/save";
$.each(myFiles, function(key, value) {
file = value;
});
var filesize = file.size;
if ((filesize/(1024*1024)) <= maxSize) {
$.ajax({
type: "PUT", //<-- https://stackoverflow.com/questions/10475313/ajax-file-upload-with-xmlhttprequest
url: myUrl,
processData: false,
contentType: false,
data: file,
beforeSend: function(xhr) {
xhr.setRequestHeader("X-File-Name", file.name);
xhr.setRequestHeader("X-File-Size", file.size);
xhr.setRequestHeader("X-myid", dataid);
},
success: function (json) {
//....
},
});
} else {
//...
}
}
found here: AJAX File Upload with XMLHttpRequest

Categories

Resources