Web API controller downloads csv but doesn't work with jQuery - javascript

I have a simple web api controller which I can navigate to through the url and it will download the .csv file. Now I am trying to write some jQuery where if you click the button it will download it but I am missing something.
public HttpStatusCode Get(string id)
{
var reportString = AskWebBusiness.Reports.GenerationQuestionReport(id);
var response = HttpContext.Current.Response;
response.ContentType = "text/csv";
response.AppendHeader("Content-Disposition", "attachment;filename=" + "Questions Report.csv");
response.Write(reportString);
return HttpStatusCode.OK;
}
This code definitely works and I can go to the URL to prompt the download.
$('.js-btn-download-content').click(function (event) {
var currentLanguage = getCulture();
var url = baseUrl + 'report/get/' + currentLanguage;
event.preventDefault();
$('.loadingContent-download').fadeIn(200);
$.ajax({
headers: {
Accept : "text/csv; charset=utf-8",
"Content-Type": "text/csv; charset=utf-8"
},
url: url,
dataType: "text/csv",
success: function (data) {
$('.loadingContent-download').fadeOut(200);
// Not sure about code below
//var xmlDoc = $.parseXML(data);
//var $xml = $(xmlDoc);
//var $title = $xml.find("200");
//if ($title) {
//$('.contentDownloaded-download p').html('Content donwloaded!');
//$('.contentDownloaded-download').show();
//} else {
//$('.contentDownloaded-download p').html('Download failed! Please try again.');
//$('.contentDownloaded-download').show();
//
}
});
$('.js-btn-confirm').click(function () {
$('.contentDownloaded-download').fadeOut(200);
});
});
As you can see, here is some javaScript that I've been using in the app to handle an OK being returned. However the browser won't download the file when this script fires. Any ideas?

In your Get(string id) method, return the HttpResponseMessage instead of just the HttpStatusCode. Also, ASP.net Web API does not ensure the state of HttpContext.Current.Response (without some wizardry code). You can do something like, change the signature to Get(HttpRequestMessage request, string id) and then call request.CreateResponse(statusCode, data).

Related

Laravel download xls file with AJAX

I can't download my XLS file via Ajax
function downloadFile(response) {
var blob = new Blob([response], {type: 'application/vnd.ms-excel'})
var url = URL.createObjectURL(blob);
location.assign(url);
}
$('#export').click(function () {
$.ajax({
type: 'POST',
url : 'factures/engagements/selected/export',
headers: {'X-CSRF-TOKEN': '{{ csrf_token() }}' },
dataType: "json",
data : {
checkboxes : checkboxValues
}
}).done(downloadFile);
});
my controller :
public function exportFacturesEngagementSelected(Request $request){
$checkboxes = $request->input('checkboxes');
$collection = collect($checkboxes);
$engagements = EngagementOrder::whereIn('id' , $collection)->get();
$date = Carbon::now('Europe/Paris')->format('d-m-Y H:i:s');
$output = Excel::create('factures_engagements' . $date. '', function($excel) use ($engagements) {
$excel->sheet('Excel', function($sheet) use ($engagements) {
$sheet->loadView('engagements.exportExcelSelected')->with("engagements", $engagements);
});
})->export('xls');
return $output;
}
I only get the output preview of the file in my console network, but nothing happens in my browser; no file is downloaded. What am I doing wrong?
UPDATE #matticustard solution :
my checkboxValues is a json for exemple the result is
{920: "920", 927: "927", 931: "931", 939: "939"}
when i console log query i get :
undefinedcheckboxes=920&checkboxes=927&checkboxes=931&checkboxes=939&
When i try to get the values to my controller i made a $request->all() and i get :
array:2 [
"undefinedcheckboxes" => "920"
"checkboxes" => "939"
]
why i get undefinedcheckboxes and why i don't get the other ids ?
Try this
if your ajax success
location.href = path/to/file/property_title.xls
change this line
->export($type);
with
->store($type, 'public/reports/', true);
These days I've used this package
(my recommendation) for converting my model's collections to XLS and export that.
As I understand, you want to download the file via AJAX. I didn't got you at all, but I just can share my experience for helping you. This working with a normal POST request, but it will not refresh your page anyway.
So this is a working example:
In Controller
public function export(Request $request)
{
$data = $request->get('data'); // get incoming data field
return \Excel::download(new ExcelService($data), "custom-file-name-with-extension.xls");
}
In Service (or you can implement this in controller too)
namespace App\Services;
use App\Models\Item;
use Maatwebsite\Excel\Concerns\FromCollection;
class ExcelService implements FromCollection
{
protected $data = null;
public function __construct($data)
{
$this->data = $data;
}
public function collection()
{
$items = Item::where('data', $data)->get(); // some query using incoming $data
return $items;
}
}
Route
Route::post('export', 'ItemController#export')->name('export');
There's really no reason to use AJAX or store the file. You can pass the checkbox data as parameters in the URL with a GET request and use an <iframe> to download the file. I guessed at the controller name, so adjust as necessary.
web.php
Change the route to GET.
Route::get('factures/engagements/selected/export', 'FactureController#exportFacturesEngagementSelected')->name('export');
JavaScript function and handler
Serialize the data as expected by your controller and make the request.
I guessed that checkboxValues was an array of values based on the actions taken in your controller. But you could serialize the form directly var query = $('form').serialize(); and adjust the controller to match the input.
function downloadFile() {
var query;
$.each(checkboxValues, function(index,value) {
query += 'checkboxes=' + value + '&';
});
$('<iframe />')
.attr('src', '/factures/engagements/selected/export?' + query)
.hide()
.appendTo('body');
}
$('#export').click(function () {
downloadFile();
});
FactureController.php
And use the download method in your controller.
// ...
->download('xls');

how to put image in json as data

i am working on a code for rest api in which i am at page "imageTest" wth a image and button "onclick event" of the button will call function "foo()"
#RequestMapping(value = "/imageUpload2/", method = RequestMethod.POST, produces = "application/json")
public ResponseEntity profilePicTest(#RequestBody String data) {
System.out.println("imageString length : " + data.length());
System.out.println("imageUpload : " + data);
return new ResponseEntity(null, HttpStatus.OK);
javascript part
function foo() {
alert('uploading image to imageupload2 url');
var profpic = document.getElementById("profpic");
alert('uploading image1122334455')
jQuery.ajax( {
url: 'http://localhost:8090/EventApp/imageUpload2/',
type: 'POST',
data: { img: profpic },
success: function( response ) {
// response
}
} ); alert('uploading done')
}
can anyone help me in the part were i can upload image by javascript (with encoding like base64) which restcontroller can accept that image string further convert into byte[] array and inserted into oracle db blob column and vice versa to send it back
------problem part----
image not uploading in json as string
please anyone help me ...!
The value of data should just be the file object from the input.
HTML
<input type="file" id="profpic" />
JS
var file = $("#profpic")[0].files[0];
jQuery.ajax( {
url: 'http://localhost:8090/EventApp/imageUpload2/',
type: 'POST',
data: file,
success: function( response ) {
// response
}
});
Note: This doesn't work in many older browsers. IE10+ is fine but anything older than that will require a different method.

Downloading Excel File via webmethod response by ajax calling

I have created a webmethod and the method just send a Excel file as webresponse.When i run only the webmethod it works fine as want
My webmethod is following:
public void Export_ex(string elem)
{
string elements = elem;
HttpContext.Current.Response.ContentType = "data:application/vnd.ms-excel";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=Print.xls");
HttpContext.Current.Response.Write("<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">");
HttpContext.Current.Response.Write("<head>");
HttpContext.Current.Response.Write("<div>");
HttpContext.Current.Response.Write("<META http-equiv=\"Content-Type\" content=\"text/html; charset=utf- 8\">");
HttpContext.Current.Response.Write("<!--[if gte mso 9]><xml>");
HttpContext.Current.Response.Write("<x:ExcelWorkbook>");
HttpContext.Current.Response.Write("<x:ExcelWorksheets>");
HttpContext.Current.Response.Write("<x:ExcelWorksheet>");
HttpContext.Current.Response.Write("<x:Name>Report Data</x:Name>");
HttpContext.Current.Response.Write("<x:WorksheetOptions>");
HttpContext.Current.Response.Write("<x:ValidPrinterInfo/>");
HttpContext.Current.Response.Write("</x:Print>");
HttpContext.Current.Response.Write("</x:WorksheetOptions>");
HttpContext.Current.Response.Write("</x:ExcelWorksheet>");
HttpContext.Current.Response.Write("</x:ExcelWorksheets>");
HttpContext.Current.Response.Write("</x:ExcelWorkbook>");
HttpContext.Current.Response.Write("</xml>");
HttpContext.Current.Response.Write("<![endif]--> ");
HttpContext.Current.Response.Write("</head>");
HttpContext.Current.Response.Write(elements);
HttpContext.Current.Response.Flush();
// HttpContext.Current.Response.End();
}
but when i call it from javascript function by ajax calling nothing happened. My ajax method is following :
var str = "something"
var data = { elem: str };
$.ajax({
type: 'POST',
url: "ImageSaving.asmx/Export_ex",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
mimeType: 'application/vnd.ms-excel',
success: function (response) {
var show = response.d;
},
failure: function (msg) {
alert("Error occur, could not load the service.");
}
});
I could not understand where i am getting wrong?? Any suggestion regarding this?
For security reasons, you cannot download file from client side. I advice to use a hidden button server side and simulate the click from another button client side.
Regards.

Calling PHP webservice method from Javascript/jQuery

I've have created a PHP web service method
public function import_external_xml($importXml)
I want to allow a client to upload xml via my web service method. My web service is not on the same domain as the client. The client has a webpage with a button where he want to write some javascript/jQuery to upload the xml via my web service method.
How can he do this?
Web service method in server.php:
public function import_external_xml($importXml)
{
echo 'import_external_xml';
exit;
}
I did the same thing using Ruby on Rails. But was sending data that was not in xml format.
One important thing as you said that your webservice is not on the same domain, you will have to deal with CORS. You can get idea about CORS here https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
You can refer this Post JQuery JSON Calls To PHP WebService Always Runs "Error" Callback
function callPhpAPI(){
var dataa = {"your_data":youdata};
$.ajax({
url : yourwebserviceurl,
type: 'POST',
data : JSON.stringify(dataa),
contentType : "application/json",
success:function(data)
{
if(data){
alert(data);
//console.log("Data from Server"+JSON.stringify(data));
}
else{
console.log("Data is empty");
}
},
error: function(xhr) {
alert('Error! Status = ' + xhr.status + " Message = " + xhr.statusText);
//console.log('Error! Status = ' + xhr.status + " Message = " + xhr.statusText);
}
});
});
You can call your php function like this using ajax
xmlDocument = $("<wrap/>").append(xmlDocument).html();
xmlDocument = encodeURIComponent(xmlDocument);
then ajax
jQuery.ajax({
type: "POST",
url: 'your_functions_address.php',
processData : false,
contentType : 'text/xml',
data : xmlDocument,
success: function (obj, textstatus) {
if( !('error' in obj) ) {
yourVariable = obj.result;
}
else {
console.log(obj.error);
}
}
});
i think you want pass xml via this ajax post , then you can refer this discussion
post xml
also check this

In .net, how can I download this remote file

I am trying to build a marquee that reads from a remote rss feed. The ajax request was failing due to what I can only assume are cross domain restrictions. Here is my code:
$(function () {
$.ajax({
url: 'http://www.theleafchronicle.com/section/news01&template=rss_weblogs&mime=xml',
dataType: 'xml',
type: 'GET',
success: function (xml) {
$(xml).each(function () {
var title = $(this).find("title").text();
var des = $(this).find("description").text() + ' - ';
var wrapper = "<span class='single-feed'></span>";
$(".feed-container").append($(wrapper).html(des));
});
},
error: function (err) { }
});
});
This code failed, so I instead tried downloading the xml locally and it worked. My only concern now is how can I download this code via batch file or possibly a .net executable? I have tried the System.Net.WebClient.DownloadFile method and it brings back a page instead of the intended xml.
class Program
{
static void Main(string[] args)
{
System.Net.WebClient wc = new System.Net.WebClient();
wc.DownloadFile("http://www.theleafchronicle.com/section/", "theleafchronicle.xml");
}
}
You can use wc.DownloadString(url) or wc.DownloadData(url) depending how you prefer the response.

Categories