Codeigniter forcedownload is redirecting to browser instead of downloading file - codeigniter-3

I have some images and each image is having a link. When I click on image one popup will open and in that popup I am displaying data in table format. In that table there is a download link. When user click on the download link, file should be download.That was my requirement. Below is my controller function to open popup and display data in table.
public function viewCommunication()
{
$post_data = $this->input->post();
$c_id = $post_data['c_id'];
$m_id = $post_data['m_id'];
$this->db->where("(c_id IN($c_id) AND mentee_id IN ($m_id))");
$query = $this->db->get('upload_checklist');
$checklist_data = $query->result();
$data['viewchecklist_data'] = json_decode(json_encode($checklist_data),TRUE);
$data4 = "";
$data4.='<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Initial Meeting</th>
</tr>
</thead>
<tbody>';
foreach($data['viewchecklist_data'] as $key=>$value){
$download_link = 'MyController/downloadFile($value['initial_meeting'])';
$data4.='<tr>
<td><a href='.$download_link.'>'.$initial_meeting.'</a></td>
</tr>';
}
$data4.='</tbody> </table>';
echo $data4;
}
// Function to download
public function downloadFile($file_name)
{
$this->load->helper('download');
$path = base_url().'upload/files/'.$file_name;
force_download($file_name,$path);
}
But When I click on download link , the download link is going to the browser url like http://localhost/project/mycontroller/downloadFile(filename.doc) like this. Where I am doing wrong? Any help would be greatly appreciated.

Related

Using GitHub list-issues-for-a-repository API

When you go to GitHub, under Issues, it pulls up all the open issues as an HTML page. We'd like to implement a dashboard showing all the issues in a repository, grouped by labels, including those issues which are not correctly labelled.
This is the corresponding list-issues-for-a-repository API.
While I was initially using jQuery and Javascript, am now using PHP for a proof-of-concept because its built-in session handling lets me use the same page to login, have GitHub authenticate & callback, and continue. But it doesn't matter to me, any language is okay.
I've managed to get access to the GitHub API via OAUTH2, but when I get the list of repositories via https://api.github.com/orgs/{org}/repos it comes up as an empty array.
Because the /orgs/{org}/repos API returns an empty array, of course the corresponding /repos/{org}/{repo}/issues API will return an error.
Edit: See this followup for a solution! Glad I finally got it working!
It is a rest API. You need to call some endpoints using an Http request.
I don't know what language you are trying to use so I can't give you a good example on how to acheive this.
If you don't know which language to use yet, use postman to create REST API call to the github API.
Let's say you want to retreive the issues of the microsoft's typescript repo, You would need to call this API endpoint :
https://api.github.com/repos/microsoft/typescript/issues
Notice here that i have replace the :owner and :repo value of documentation for the one i'm trying to get.
You can then pass some parameters to the call to filter your data, for example, the API label.
https://api.github.com/repos/microsoft/typescript/issues?labels=API
This will only return issues that are labelled as API.
This is the basics of how to use an API.
You can use jQuery Ajax to access the Github API and add a basic authentication header to authenticate (see here), an example is shown below, this will pull the issues for a given repo and show the first 10 in an alert window.
See the documentation on pulling issues here: https://developer.github.com/v3/issues/ to see which parameters you can use to filter, sort etc.
For example you can get all issues labelled 'bug' using:
/issues?labels=bug
This can include multiple labels, e.g.
/issues?labels=enhancement,nicetohave
You could easily modify to list in a table etc.
const username = 'github_username'; // Set your username here
const password = 'github_password'; // Set your password here
const repoPath = "organization/repo" // Set your Repo path e.g. microsoft/typescript here
$(document).ready(function() {
$.ajax({
url: `https://api.github.com/repos/${repoPath}/issues`,
type: "GET",
crossDomain: true,
// Send basic authentication header.
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(username + ":" + password));
},
success: function (response) {
console.log("Response:", response);
alert(`${repoPath} issue list (first 10):\n - ` + response.slice(0,10).map(issue => issue.title).join("\n - "))
},
error: function (xhr, status) {
alert("error: " + JSON.stringify(xhr));
}
});
});
Below is a snippet listing issues for a (public) repo using jQuery and the Github API:
(Note we don't add an authentication header here!)
const repoPath = "leachim6/hello-world" //
$(document).ready(function() {
$.ajax({
url: `https://api.github.com/repos/${repoPath}/issues`,
type: "GET",
crossDomain: true,
success: function (response) {
tbody = "";
response.forEach(issue => {
tbody += `<tr><td>${issue.number}</td><td>${issue.title}</td><td>${issue.created_at}</td><td>${issue.state}</td></tr>`;
});
$('#output-element').html(tbody);
},
error: function (xhr, status) {
alert("error: " + JSON.stringify(xhr));
}
});
});
<head>
<meta charset="utf-8">
<title>Issue Example</title>
<link rel="stylesheet" href="css/styles.css?v=1.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.4.1.min.js" crossorigin="anonymous"></script>
</head>
<body style="margin:50px;padding:25px">
<h3>Issues in Repo</h3>
<table class="table table-striped">
<thead>
<tr>
<th scope="col">Issue #</th>
<th scope="col">Title</th>
<th scope="col">Created</th>
<th scope="col">State</th>
</tr>
</thead>
<tbody id="output-element">
</tbody>
</table>
</body>

test list of dynamically created table headers using protractor and angular 6

I am using protractor with angular 6. stuck in a situation where i want to write test case to test a list of table headers which are created with data coming from backend called in ngOnInit.
i tried using tick and fakeAsync but keep on getting error
Failed: Cannot read property 'assertPresent' of null
below is my code:
app.po.ts
goToScannersList() {
return browser.get('/scanners');
}
getScannersList() {
let items = element.all(by.css('.scannerlist th')).map(function (elm) {
return elm.getText();
});
return items;
}
If i use spec like in 1) i get error mentioned above even if i remove page.goToScannersList();
but if use spec like in 2) my test is success irrespective of what value it returns.
1)
app.e2e-spec.ts
it('should display list of scanners', fakeAsync(() => {
page.goToScannersList();
tick(4000);
expect(page.getScannersList()).toEqual([
"ScannerID",
"Desc",
"Owner"
]);
}));
2)
app.e2e-spec.ts
it('should display list of scanners', () => {
page.goToScannersList();
fakeAsync(()=>{
tick(4000);
expect(page.getScannersList()).toEqual([
"ScannerID",
"Desc",
"Owner"
]);
})
});
scanners.component.html
<table class="scannerlist" id="scannersList" style="text-align:center;width:100%">
<thead>
<tr ><th *ngFor="let col of scannerKeys">{{col}}</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let row of scannerData">
<td>{{row.ScannerID}}</td>
<td>{{row.Desc}}</td>
<td>{{row.Owner}}</td>
</tr>
</tbody>
</table>
scanners.component.ts
ngOnInit() {
this.scannerService.getScannerDetails().subscribe((data)=>{
this.scannerData = data.Data;
this.scannerKeys = this.getKeys(data.Data[0]);
});
}
let me know if anybody has any idea how to implement it. thanks in anticipation.

DataTables cannot recognize data from DOM

I have this simple table and the tbody fills with loadLogsTable(); function
<table id="logsTable" style="width:100%;text-align:center;">
<thead>
<th style="width:9%;">Choose</th>
<th style="width:15%;">Ip</th>
<th style="width:15%;">Hostname</th>
<th style="width:50%;">Log</th>
<th style="width:15%;">Date</th>
</thead>
<tbody id="logData"></tbody>
</table>
Here is the loadLogsFunction:
function loadLogsTable()
{
jQuery.ajax({
type: "POST",
async : true,
url: "classes/classesController.php",
data: { method: "getLogsList"},
contentType : ('application/x-www-form-urlencoded'),
dataType : "html" ,
success : function(data){
$("#logData").html(data);
}
});
}
I initialize this table with dataTables but it doesn't paginate them (i have choose 10 rows per page) and it looks like it cannot see table's data. I also cannot search in table's data.
$(document).ready(function()
{
loadLogsTable();
$('#logsTable').dataTable({ // Init pagination
"aoColumnDefs": [{ "bSortable": false, "aTargets": [ 0,1,2,3,4] } ],
"sPaginationType": "full_numbers" ,
"bLengthChange": false,
iDisplayLength": 10
});
});
Issue 1: your iDisplayLength is not properly enclosed by quotes.
You have:
iDisplayLength": 10
but you will avoid an error if instead you have:
"iDisplayLength": 10
That should eliminate your javascript errors.
http://jsfiddle.net/MmDFN/1/
Issue 2: have you examined the ajax data source and server-side processing examples on the datatables site, or looked at mrender? I can't say the way you are using ajax with datatables is conventional.
http://www.datatables.net/examples/
http://www.datatables.net/ref#mrender
mg1075 is right the iDisplayLength was missing a quote.
http://jsfiddle.net/nr5Cw/2/
"<--missing

How to upload file to folder on server in jsp? [duplicate]

This question already has answers here:
How can I upload files to a server using JSP/Servlet?
(14 answers)
Closed 2 years ago.
I am doing project Online Image Gallery, in which I have to upload images. I am doing it with jsp/servlet and IDE is Eclipse.
My Jsp file is as follows
<form action="ActionPage" >
<input type="file" name="myFile">
<br>
<input type="submit">
</form>
Here Actionpage is servlet. On Clicking submit button i want the selected file to be stored inside the folder called "IMAGE" inside the WebContent on server and path on database table.
If any one know the simple solution please share it.
Thanks in advance.
You can read how this is done here
How to upload files to server using JSP/Servlet?
PS: Storing uploaded files inside the applications directory is BAD BAD BAD idea. Think about what would happen if you have your application running for some time, and you want to do a redeploy becase a file is missing some html tag. The upload's directory will be removed by your container!
Try using a folder outside of the application's directory, or use a database.
This is the easiest solution if You are using jsp to develop your website
First of all for taking input from user make a html or jsp page and include tis code in your jsp/html page
First of all download
commons-fileupload-1.2.2.jar
org.apache.commons.io.jar
and add this jar to your library by right-clicking your project then select build path and then add jar files
`<form role="form" action="Upload.jsp" method="post"enctype="multipart/form-data">
<div class="btn btn-success btn-file">
<i class="fa fa-cloud-upload"></i>
Browse
<input type="file" name="file" />
</div>
<button type="submit" value="submit" name='submit'>submit</button>`
</form>
enctype="multipart/form-data"
it is necessary
Now make one jsp named upload.jsp( you can have the target jsp with which we are going to save our image to server of any name but remember to put that name in in above code
<%# page import="java.io.*,java.util.*, javax.servlet.*" %>
<%# page import="javax.servlet.http.*" %>
<%# page import="org.apache.commons.fileupload.*" %>
<%# page import="org.apache.commons.fileupload.disk.*" %>
<%# page import="org.apache.commons.fileupload.servlet.*" %>
<%# page import="org.apache.commons.io.output.*" %>
<%
String userName = (String) session.getAttribute("User");
File file ;
int maxFileSize = 5000000 * 1024;
int maxMemSize = 5000000 * 1024;
ServletContext context = pageContext.getServletContext();
String filePath = context.getInitParameter("file-upload");
// Verify the content type
String contentType = request.getContentType();
if ((contentType.indexOf("multipart/form-data") >= 0)) {
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("C:\\Users\\"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );
try{
// Parse the request to get file items.
List<FileItem> fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String fileName = fi.getName();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if( fileName.lastIndexOf("\\") >= 0 ){
file = new File( filePath +
fileName.substring( fileName.lastIndexOf("\\"))) ;
}else{
file = new File( filePath +
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write( file ) ;
request.setAttribute("Success", "Successfully Uploaded");
RequestDispatcher rd = request.getRequestDispatcher("/UploadFiles.jsp");
rd.forward(request, response);
}
}
}catch(Exception ex) {
System.out.println(ex);
}
}else{
request.setAttribute("Error", "Error!!");
RequestDispatcher rd =request.getRequestDispatcher("/UploadFiles.jsp");
rd.forward(request, response);
}
%>
please don't get confused just copy this code and once you go through this i am sure you will get to know about code
Now the last thin you have to do is to add something to web.xml if you don't have this file then create this...
<context-param>
<description>Location to store uploaded file</description>
<param-name>file-upload</param-name>
<param-value>
C:\\Users\\
</param-value>
</context-param>
just add above code to web.xml you can change the address where your images will be uploaded as desired ( change param-value for this)
In case you face any problem let me know

WebSockets on iOS

I've read that WebSockets work on iOS 4.2 and above. And I can verify that there is indeed a WebSocket object. But I can't find a single working WebSocket example that works on the phone.
For example http://yaws.hyber.org/websockets_example.yaws will crash the Mobile Safari app. Has anyone got WebSockets working successfully on the phone?
I may have found the solution. Mobile Safari only crashes with websockets when you have setup a proxy over wifi.
It is supported, but bear in mind regarding the standard that iOS Safari browser implements, it is not RFC 6455, but HyBi-00/Hixie-76.
You can test as well using this browser: http://websocketstest.com/
As well check this great post that have most of info regarding versions: https://stackoverflow.com/a/2700609/1312722
OBS!, this is an old answer.
I have checked through the webpage mentioned in this post combined with browserstack.com:
iPhone4S
iPhone5
iPhone5S
iPhone6
iPhone6 Plus
iPhone6S
iPhone6S Plus
All using RFC 6455
I had a similar problem and even looked to this post to find a fix for it. For me, it had nothing to do with being on a wifi connection. It appears to be a bug in the iOS implementation of websockets (even up to the current version 5.1). Turning on a bunch of XCode's debugging I found that it has something to do with memory management because I would get something along the lines of "message sent to a deallocated instance." Most likely there was an object that didn't have the correct reference count and was cleaned up way too early.
This blog has a lot of great information about the symptoms of the problem and how to debug it, but doesn't have a workaround: http://dalelane.co.uk/blog/?p=1652
Eventually though, I found this workaround, and my app has almost entirely stopped crashing now.
me = this // strange javascript convention
this.socket = new WebSocket(url);
// put onmessage function in setTimeout to get around ios websocket crash
this.socket.onmessage = function(evt) { setTimeout(function() {me.onMessageHandler(evt);}, 0); };
I got them working on Chrome and Safari, iPhone and iPad (and other mobile devices too, but I guess you don't mind about them). Here is the Javascript code I am using :
<script language="javascript" type="text/javascript">
var wsUri = document.URL.replace("http", "ws");
var output;
var websocket;
function init()
{
output = document.getElementById("output");
wsConnect();
}
function wsConnect()
{
console.log("Trying connection to " + wsUri);
try
{
output = document.getElementById("output");
websocket = new WebSocket(wsUri);
websocket.onopen = function(evt)
{
onOpen(evt)
};
websocket.onclose = function(evt)
{
onClose(evt)
};
websocket.onmessage = function(evt)
{
onMessage(evt)
};
websocket.onerror = function(evt)
{
onError(evt)
};
}
catch (e)
{
console.log("Exception " + e.toString());
}
}
function onOpen(evt)
{
alert("Connected to " + wsUri);
}
function onClose(evt)
{
alert("Disconnected");
}
function onMessage(evt)
{
alert('Received message : ' + evt.data);
}
function onError(evt)
{
alert("Error : " + evt.toString());
}
function doSend(message)
{
websocket.send(message);
}
window.addEventListener("load", init, false);
Sending data from client to server is done calling doSend() function. Receiving data from server also works, I've tested it from a custom C++ server.
Here is a working sample
Web socket client
<!DOCTYPE html>
<meta charset="utf-8" />
<head>
<title>WebSocket Test</title>
<script language="javascript" type="text/javascript">
var websocket;
function OpenWebSocket()
{
try {
websocket = new WebSocket(document.getElementById("wsURL").value);
websocket.onopen = function(evt) { onOpen(evt) };
websocket.onclose = function(evt) { onClose(evt) };
websocket.onmessage = function(evt) { onMessage(evt) };
websocket.onerror = function(evt) { onError(evt) };
}
catch(err) {
writeToScreen(err.message);
}
}
function CloseWebSocket()
{
websocket.close();
}
function FindWebSocketStatus()
{
try {
if (websocket.readyState == 1){
writeToScreen("Websocket connection is in open state")
}
else if (websocket.readyState == 0){
writeToScreen("Websocket connection is in connecting state")
}
else{
writeToScreen("Websocket connection is in close state")
}
}
catch(err) {
writeToScreen(err.message);
}
}
function FindWebSocketBufferedAmount(){
try {
writeToScreen(websocket.bufferedAmount)
}
catch(err) {
writeToScreen(err.message);
}
}
function SendMessageThroughSocket(){
doSend(document.getElementById("wsMessage").value);
}
function onOpen(evt)
{
writeToScreen("Socket Connection Opened");
}
function onClose(evt)
{
writeToScreen("Socket Connection Closed");
}
function onMessage(evt)
{
writeToScreen('<span style="color: blue;">SERVER RESPONSE: ' + evt.data+'</span>');
}
function onError(evt)
{
writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
}
function doSend(message)
{
try{
writeToScreen("CLIENT SENT: " + message);
websocket.send(message);
}
catch(err) {
writeToScreen(err.message);
}
}
function writeToScreen(message)
{
var output = document.getElementById("output");
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}
</script>
</title>
</head>
<body>
<table>
<tr>
<td>
WebSocket URL
</td>
<td>
<input type="text" id="wsURL" value="ws://echo.websocket.org/"/>
</td>
</tr>
<tr>
<td>
WebSocket Message
</td>
<td>
<input type="text" id="wsMessage" value="Hi"/>
</td>
</tr>
<tr>
<td colspan="2" style="text-align:left;">
<input type="button" value="Open Socket Connection" onclick="OpenWebSocket();"/>
</td>
</tr>
<tr>
<td colspan="2" style="text-align:left;">
<input type="button" value="Send Message" onclick="SendMessageThroughSocket();"/>
</td>
</tr>
<tr>
<td colspan="2" style="text-align:left;">
<input type="button" value="Close Socket Connection" onclick="CloseWebSocket();"/>
</td>
</tr>
<tr>
<td colspan="2" style="text-align:left;">
<input type="button" value="Find Socket Status" onclick="FindWebSocketStatus();"/>
</td>
</tr>
<tr>
<td colspan="2" style="text-align:left;">
<input type="button" value="Find Socket Buffered Amount" onclick="FindWebSocketBufferedAmount();"/>
</td>
</tr>
</table>
<div id="output"></div>
</body>
</html>
Web Socket server
Creating your own socket server is also simple Just install the Node.js and socket.io then proceed to install web socket via npm
#!/usr/bin/env node
var WebSocketServer = require('websocket').server;
var http = require('http');
var server = http.createServer(function(request, response) {
console.log((new Date()) + ' Received request for ' + request.url);
response.writeHead(404);
response.end();
});
server.listen(8888, function() {
console.log((new Date()) + ' Server is listening on port 8888');
});
wsServer = new WebSocketServer({
httpServer: server,
// You should not use autoAcceptConnections for production
// applications, as it defeats all standard cross-origin protection
// facilities built into the protocol and the browser. You should
// *always* verify the connection's origin and decide whether or not
// to accept it.
autoAcceptConnections: false
});
function originIsAllowed(origin) {
// put logic here to detect whether the specified origin is allowed.
return true;
}
wsServer.on('request', function(request) {
if (!originIsAllowed(request.origin)) {
// Make sure we only accept requests from an allowed origin
request.reject();
console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
return;
}
var connection = request.accept();
console.log((new Date()) + ' Connection accepted.');
connection.on('message', function(message) {
if (message.type === 'utf8') {
console.log('Received Message: ' + message.utf8Data);
connection.sendUTF('Message received at server:'+message.utf8Data);
}
else if (message.type === 'binary') {
console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
connection.sendBytes(message.binaryData);
}
});
connection.on('close', function(reasonCode, description) {
console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
});
});
save the above file as .js and run it like node filename.js from terminal or command prompt
The above file is like we have first created a http server using node then we're passing the created http server instance to Websocketserver then subsequently to Socket.iO instance
I was debugging a similar issue and found that if you have used https to get the web page iOS will trap if you use the pass a the "ws:" protocol into WebSocket. If you use "wss:" everything will work and there will be no traps.