Save php generated excel in react - laravel

I'm using laravel excel package to generate xls file. When I'm sending get request I can see excel file in my response(random characters), however there is no prompt to save it(I guess react blocking it on front end). What would be the right way to implement it?
React onclick listener:
function handleClick(e) {
e.preventDefault();
$.get('excel', function(data) {
//alert(data);
});
}
Laravel controller:
public function generateExcel()
{
return Excel::create('Filename', function($excel) {
$excel->sheet('Sheetname', function($sheet) {
// Sheet manipulation
});
})->download('xls');
}

Yes, react is blocking your download. The download prompt happens because of the HTTP headers. So, guessing you have a laravel url for you xls like /laravel/get/xls you should have.
Get Xls
In this way you'll open a new tab in which the http headers will prompt for the download.

Related

How do i request an Array from the controller from inside a javascript code

I am using Spring boot, JPA with mysql, and thymeleaf and openlayers for the map.
So i have a map, and on this map there are dynamically generated markers for different places. What I want is when I click any of those markers to send the name of the marker to my controller and in response get an array of fishes that can be caught in this specific area and then display the names and pictures of the fishes in a dynamically generated list located on the sidebar . I cant think on how I can achieve that. Ive made a HTML page to show how I want it to look.
I was thinking about making a get request and giving the name as a path variable but then idk how I can do that request from the javascript when the button is clicked. Any ideas or concepts that I can read about are apreciated.
Most DOM elements in html are accessible in javascript via something like document.getelementbyid and typically if I remember this correctly most of the objects you can do something like domobject.addEventListener("click", myScript); and in myScripy make an http call to spring requesting the list of fish. I recommend setting some breakpoints in your JavaScript code via the dev console in your browser and looking through some of the objects that are produced
You can make a get request like described here. developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
Clicking on the markers would be similar to this example https://openlayers.org/en/latest/examples/icon.html, but instead of showing a popup you make a GET request for more data
map.on('click', function (evt) {
const feature = map.forEachFeatureAtPixel(evt.pixel, function (feature) {
return feature;
});
if (feature) {
const name = feature.get('name');
// now make get request
// ....
}
});
If you are requesting an image you could use xhr as in https://openlayers.org/en/latest/apidoc/module-ol_Tile.html#~LoadFunction or you could use fetch, similar to:
fetch(url).then(function(response) {
if (response.ok) {
return response.blob();
}
}).then(function(result) {
if (result) {
const imagesrc = URL.createObjectURL(result);
}
});

Downloaded Excel file with Macros is corrupted via MVC ajax

I am trying to download an Excel file from MVC Ajax call, but everytime it downloads, I cannot open the file, because it says it is corrupted.
Following is my Ajax call:
function Download() {
$.ajax({
url: '/Home/ExcelDownload',
type: "POST",
success: function (result) {
if (result !== null || result !== "") {
$('<iframe src=' + result + ' frameborder="0" scrolling="no" id="myFrame"></iframe>')
.appendTo('body');
}
//var iframe = document.getElementById('invisible');
//iframe.src = result;
},
error: function (data) {
}
});}
From my controller I call the action method like this:
string host = Request.Url.Authority;
return Json("http://" + host + "/ExcelTemplates/EInvoiceTemplateNew.xlsm");
I am having macros enabled in Excel as well.
The file downloads properly but when I try to open it, it gives me a warning about being from a trusted source, and on clicking yes, I get another dialog saying "The workbook cannot be opened or repaired By Microsoft excel because it is corrupt".
Any help or suggestions or workarounds to make my code working.
Thanks In Advance!!!..
I'm not able to do a project and try the excel library right now as I'm at work, so I'm just doing this much quickly.
To start, I think you can get away from using ajax completely. Which is always nice because it's less code to maintain, you can use a normal anchor tag:
Download
This won't redirect the page, because the browser should interpret the content-disposition/Mime type, and just download the file.
Then you can try returning the file like this, where you first read the file (in this case into a stream, but you could do it as a byte[] as well as File has a overload for it), and then return it through your controller by using File and FileResult.
E.g:
public FileResult GetExcelDocument(int id)
{
string filePath = GetPathToDocumentWithId(id); //However you get the excel file path
return File(System.IO.File.OpenRead(filePath),
System.Web.MimeMapping.GetMimeMapping(filePath),
"filename.xlsm");
}
This website says that the content type/MIME of .xlsm is "application/vnd.ms-excel.sheet.macroEnabled.12", but I think GetMimeMapping should work.
Optionally, if you want the file to download in a new tab, you can set the target of the anchor tag to "_blank" and it should open a new tab and download the file there.
Let me know what the result is.
If you're set on using JQuery and ajax, I found this example which follows along your previous attempt:
From Here
var $idown; // Keep it outside of the function, so it's initialized once.
downloadURL : function(url) {
if ($idown) {
$idown.attr('src',url);
} else {
$idown = $('<iframe>', { id:'idown', src:url }).hide().appendTo('body');
}
},

Laravel+Vue routing

I am using Laravel+VueJs. I stuck on one thing. I am trying to load a new view using laravel route. I am using axios.
getRelatedChat(id) {
return axios.get('/chat/'+id).then(({ data }) => {
// document.write(data)
});
}
The code of whole view is coming in console as output, but i want to load it like window.url does for us. Have no idea how to do.
Vue has its own router. If you want to load a new page you can still use axios to get the data you want to show in the next page you want to open. Just try the Vue Router
I was making a nonsense. Actually there is no need to load the view. I can update some variable that are using on present component just like this:
axios.get('/chat/json/'+id).then(({ data }) => {
this.messages =data.messages;
this.withUser = data.user;
}

Can't download file with open bootstrap Modal

I have an AngularJS front-end that opens a Bootstrap Modal that has a button on it. When this button is clicked it calls a Web API method on the server that generates an OPEN XML Word Document as a stream and returns the file to the client. I have several files downloading successfully in IE where I see this:
However, for the file I'm trying to download with the open Modal I never see the above image. It's not the file itself because it downloads successfully when I try it without the open Modal. Also, I don't see any errors reported in IE Dev Tools. I don't think it's the code that generates the streams because the same code generates other files successfully. I also tried closing the Modal before downloading but that didn't work either. It's almost like the Modal is "blocking" the download.
Here is the Modal definition:
var isOUOModal;
var isSubmitItem = false;
var openSignificanceModal = function () {
return $modal.open({
scope: $scope,
templateUrl: './app/oa/significance_modal.html',
controller: SignificanceModalCtrl,
keyboard: false,
backdrop: 'static',
resolve: {
item: function () {
return $scope.item;
}
}
});
};
var SignificanceModalCtrl = function ($scope, $modalInstance, item, $window) {
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
};
I seem to be out of ideas at the moment so any assistance is much appreciated.
Thanks,
Pete
I was able to determine the cause of the problem here. It had to do with the way I was calling the Web API Method. I was using an AJAX JQuery GET call. Instead I had to do something like this:
var url = url;
window.location.href = url;
When I changed the way I was calling the Web API method I saw the stream returned to the client as expected.

Asp MVC 3 download a zipped file

I have a view with a generate button. When I click It I am navigating to a Generate method of a controller using ajax call.
generate = function () {
$.ajax({
url: "/franchise/Generate",
type: "POST",
data: { id: omega.franchiseInfo.Id(), imagesPath: omega.franchiseInfo.ImagesPath() },
});
}
Here is my Generate method:
public ActionResult Generate(int id, string imagesPath)
{
// some logic here
var zipFileName = #"D:\FranchiseGeneration\MyZipFile.zip";
using (var zip = new ZipFile())
{
zip.AddDirectory(#"D:\FranchiseGeneration\Test", "Generation");
zip.Save(zipFileName);
}
return File(zipFileName, "application/zip", "MyZipFile.zip");
}
MyZipFile.zip is created on my hard drive as specified. I expect the user to be prompted to download the zipped file ... but nothing happens. I am rather new to Mvc3 and I am not sure what I am doing wrong. Any suggestions with code samples are welcome. Thank You!
It's an ajax call, it doesn't make sense to return a File in an ajax call... ajax stands for Asynchronous JavaScript and XML.. ok with json ad some other text based things, but to work with binary files you'll need some exta works.
In you scenario, I think the best thing to do (the simplest one) is to perform a normal postback, not ajax (or even a simple GET would work).
It is not possible to trigger a file download via an ajax request like this.
There are other ways to make something like it happen though.
http://johnculviner.com/post/2012/03/22/Ajax-like-feature-rich-file-downloads-with-jQuery-File-Download.aspx

Resources