How to dynamically upload multi-part form data using JavaScript - javascript

I am trying to upload a file to server using JavaScript as dynamically generating a form along with input file while clicking a button.
But here, uploading File is not appending to form tag inside the script, so that upload function not works.
My code in html file as follows,
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Upload</title>
</head>
<body>
<div id="formActive">
<button onclick="imageContent();">click</button>
</div>
<script>
function imageContent(){
var imgContent = "file";
var fileContent = document.createElement('input');
fileContent.name = 'file';
fileContent.type = 'hidden';
var lastImageFile = "imageName";
var boundary=Math.random().toString().substr(2);
multipart = "--" + boundary
+ "\r\nContent-Disposition: form-data; name=" + lastImageFile
+ "\r\nContent-type: application/octet-stream"
+ "\r\n\r\n" + imgContent + "\r\n";
multipart += "--"+boundary+"--\r\n";
fileContent.value = imgContent;
var form = document.createElement('form');
form.method = "POST";
form.action = "mydomain.com/upload";
form.enctype = "multipart/form-data";
form.appendChild(fileContent);
document.getElementById("formActive").appendChild(form);
form.submit();
}
</script>
</body>
</html>
While looking into the upload servlet, I didn't get any file name in request.
Can anyone assist that where I did mistake?

Related

How to save contact details from a website to an android or iphone using HTML button with JS or PHP integration?

I'm trying to implement a functionality in a website so a user can save the contact details from a website to their phone (android/iPhone) by clicking on an HTML button.
This is what I tried so far
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="save-btn">Save Contact</button>
<script src="script.js"></script>
</body>
</html>
JavaScript Code
var saveBtn = document.getElementById("save-btn");
saveBtn.addEventListener("click", function () {
// Get the contact information from the website
var contact = {
name: "John Doe",
phone: "111551144111",
email: "john#doe.com"
};
// create a vcard file
var vcard = "BEGIN:VCARD\nVERSION:4.0\nFN:" + contact.name + "\nTEL;TYPE=work,voice:" + contact.phone + "\nEMAIL:" + contact.email + "\nEND:VCARD";
var blob = new Blob([vcard], { type: "text/vcard" });
var url = URL.createObjectURL(blob);
saveBtn.href = url;
saveBtn.download = contact.name + ".vcf";
});
For testing purpose, I uploaded this on a webserver but nothing is happening.
https://cheery-taiyaki-477ee0.netlify.app
You are very close. The trick is to make a new link and set that to your stuff, then click that:
var saveBtn = document.getElementById("save-btn");
saveBtn.addEventListener("click", function () {
// Get the contact information from the website
var contact = {
name: "John Smith",
phone: "555-555-5555",
email: "john#example.com"
};
// create a vcard file
var vcard = "BEGIN:VCARD\nVERSION:4.0\nFN:" + contact.name + "\nTEL;TYPE=work,voice:" + contact.phone + "\nEMAIL:" + contact.email + "\nEND:VCARD";
var blob = new Blob([vcard], { type: "text/vcard" });
var url = URL.createObjectURL(blob);
const newLink = document.createElement('a');
newLink.download = contact.name + ".vcf";
newLink.textContent = contact.name;
newLink.href = url;
newLink.click();
});
Demo: https://codepen.io/cjhaas/pen/jOpYYvq

LinkedIn Learning LTI failed authentication

I'm attempting to integrate LinkedIn Learning Single-Sign-On via an LTI connection, however I'm always faced with the response: LTI_FAILED_AUTHENTICATION.
LinkedIn Learning - LTI_FAILED_AUTHENTICATION
When I test it out on the Saltire test platform, it strangely works.
The parameters match what I am sending from the code below:
Saltire LTI Success authentication
Have tried copying over the the values of oauth_nonce, timestamp and oauth_signature from Saltire to my page, and that worked also, which scores out the possibility of domain whitelisting requirement.
LinkedIn support have come back saying there seems to be something wrong with the generated signature, but I'm not sure what is wrong about it, since that is generated by the parameters passed.
Is there something incorrectly setup from my page which I am not seeing?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="robots" content="noindex" />
<title>Access LinkedIn Learning</title>
<script src="bundle.js"></script>
</head>
<body>
<form id="id_frmConnect" name="frmConnect" enctype="application/x-www-form-urlencoded">
</form>
<script>
var oauth = require('oauth-sign');
var action = 'https://www.linkedin.com/checkpoint/enterprise/login/[accountID]?application=learning&redirect=https://www.linkedin.com/learning/me';
var method = 'POST';
var consumer_key = '************';
var consumer_secret = '************';
var timestamp = Math.round(Date.now() / 1000);
var params = {
lti_message_type: 'basic-lti-launch-request',
lti_version: 'LTI-1p0',
oauth_callback: 'about:blank',
oauth_consumer_key: consumer_key,
oauth_nonce: btoa(timestamp),
oauth_signature_method: 'HMAC-SHA1',
oauth_timestamp: timestamp,
oauth_version: '1.0',
user_id: 'S495696'
};
var signature = oauth.hmacsign(method, action, params, consumer_secret);
params.oauth_signature = signature;
var form = document.querySelector("#id_frmConnect");
form.action = action;
form.method = method;
for (var name in params) {
var node = document.createElement("input");
node.type = 'hidden';
node.name = name;
node.value = params[name];
form.appendChild(node);
}
</script>
</body>
</html>
I figured out the issue. By using the Saltire test tool, I was able to verify that my signature was generated correctly when using their testing URL: https://lti.tools/saltire/tp
You can play with an example here: https://learningcom.github.io/ltitest/index.html
So after looking at the LinkedIn URL, I discovered that the signature was getting generated with an unnecessary long URL which contained parameters.
Removed: ?application=learning&redirect=https://www.linkedin.com/learning/me
Therefore, I shortened the URL to:
var action = 'https://www.linkedin.com/checkpoint/enterprise/login/[accountID]';
No more errors!

send parameter from js file to jsp file with ajax

Here is my js file where my goal is to send variable va to jsp file and output it. The problem I can't find the bug.
$(function(){
$("td").click(function(){
var date = $(this).html();
var message = prompt(year+"year "+month+"month "+ date+"day","null!");
this.append(message);
var variable = "mememem";
var sendData = new XMLHttpRequest();
sendData.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert("connected to server");
}
};
sendData.open('GET','dataFile.jsp?na='+variable,true);
sendData.send(null);
window.location = "dataFile.jsp";
})
});
///////////////////////////javascript file//////////////////////
<%# page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
<%
String name = request.getParameter("na");
out.print(name);
%>
</body>
</html>
///////////////////jsp file
I think the problem is you're sending variable instead of va.
This line:
sendData.open('GET','dataFile.jsp?na='+variable,true);
Hope that is the root cause of your problem.

Why is not the control moving to the script method "checkExistence()"?

I am doing a file upload program in which i am using ajax call to check whether any file exists with the same name.
Here is the code
jsp page
<%# taglib prefix = "form" uri = "http://www.springframework.org/tags/form"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Upload Example</title>
<script src="/AjaxWithSpringMVC2Annotations/js/jquery.js"></script>
<script type="text/javascript">
function checkExistence() {
var name = $('#file').val();
File f=new File(name);
var filename=f.getOriginalFileName();
document.write(filename);
$.ajax({
type: "POST",
url: "/FileController/fileexists",
data: "filename=" + filename,
success: function(response){
if(response==0)
{
ch="zero";
document.fileform.choice.value=ch;
document.fileform.submit();
}
else if(response==1)
{
alertchoice=alert("File already exists !! Do you want me to overwrite it ?");
if(alertchoice==true || alertchoice.equals(true))
{
ch="one";
document.fileform.choice.value=ch;
document.fileform.submit();
}
else {
ch="two";
alert("Upload suspended as requested by the user ");
} }
},
error: function(e){
alert('Error: ' + e);
}
});
}
</script>
</head>
<body style="background-color:powderblue;color:Tomato">
<br>
<br>
<center><form name="fileform" action="savefile" method = "POST" modelAttribute = "fileUpload"
enctype = "multipart/form-data">
Please select a file to upload :
<input type = "file" name = "file" id="file"><br><br><br>
<input type="hidden" name="choice">
<input type = "button" value ="upload" onClick="checkExistence()">
<input type="reset" value="Reset">
</form></center>
<br>
<br>
<br>
<center><b> ${message} </b></center>
</body>
</html>
//controller class
#RequestMapping(value="/fileexists",method = RequestMethod.POST)
#ResponseBody public String checkingForDuplicates(HttpServletRequest req, HttpServletResponse res){
String filename=req.getParameter("filename");
int i=isDuplicate(filename);
return i+"";
}
Here when i am clicking the button upload , control should go to the function checkExistence() . But it is not moving. Is something wrong with my code ? And i am using
File f=new File(name);
var filename=f.getOriginalFileName();
in javascript function to get the name of the file being uploaded. Does it work ?
I got the answer by making the following corrections.
Including jquery plugin
changing ajax call url from
url: "/FileController/fileexists"
to
url: "fileexists"
In jsp page to get name of the file being uploaded
var name = $('#file').val();
File f=new File(name);
var filename=f.getOriginalFileName();
modified :
var filename=document.getElementById('file').value;
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
originalfilename = filename.substring(lastIndex +1);
}
In controller to get the file name(for checking duplicates)
previous : String filename=req.getParameter("filename");
modified : String filename=req.getParameter("originalfilename");

Google Chrome Extension POST VS GET

This is my code
chrome.windows.create({'url': "http://example.com/upload/upload.php?pictureID="+ theResponse + "&userID=" + localStorage["id"]+"&username="+ localStorage["mainLogin"]}, function(tab) {
// open window
});
this constructs a URL that looks like:
http://example.com/upload/upload.php?pictureID=123&userID=1&username=jack
I would call this method GET -- like how forms GET or POST
How can I open a window with POST data rather than GET data?
I think you have to write a HTML page that creates a form containing your POST data and target URL and submit the form.
Here's a simple example:
<html>
<head>
<script>
document.addEventListener('DOMContentLoaded', function()
{
location.search.substr(1).split('&').forEach(function(item)
{
var input = document.createElement('input');
input.type = 'hidden';
input.name = item.substr(0, item.indexOf('='));
input.value = item.substr(item.indexOf('=') + 1);
document.getElementById('postform').appendChild(input);
});
document.getElementById('postform').submit();
});
</script>
</head>
<body>
<form action="http://example.com/upload/upload.php" method="post" id="postform">
</form>
</body>
</html>
Say that's test.html in your extension's root directory. Call
chrome.windows.create({'url': "test.html?pictureID="+ theResponse + "&userID=" + localStorage["id"]+"&username="+ localStorage["mainLogin"]}, function(tab) {
// open window
});
will open the website with POST method.

Categories