I have done a lot of research on how to do this, yet I can't seem to find a specific answer. I am trying to allow the user to input a file from their computer, and turn that file into the background of the webpage. My following code is shown below:
<head>
<script>
function changeBackground() {
var input = document.getElementById("background").value;
localStorage.setItem("Background", input);
var result = localStorage.getItem("Background");
$('body').css({ 'background-image': "url(" + result + ")" });
}
</script>
</head>
<body>
<input id="background" type="file" onchange="changeBackground()">
</body>
If someone could please explain to me what I need to do to get this to work, I would very much appreciate it. I already understand I need to use localStorage to make sure that the selected background is remembered, I am just having trouble getting the background to change. If there is already an article on how to do this, I would appreciate a link to it. Thanks!
EDIT
Nikhil and user6003859 explained to me why it isn't working. I guess I just need to figure out how to use Ajax and PHP to change it. If anyone has more advice on this, I would love to hear it. Thanks everyone for helping me solve this problem.
Modern browsers normally restrict access to the user's local files (in this case an image). What you're trying to do is display an image from the user's local filestorage, via the path you get from the <input type='file' /> value.
What you should instead be doing, is uploading the image to your server (probably with ajax, so it feels seamless), and then displaying the file from your server on to your page.
EDIT: Even though this is kind of a new question, I'll give you an example on how to change an element's background based on a URL provided by the user:
var inp = document.getElementById('inp');
var res = document.getElementById('res');
inp.oninput = function()
{
res.style.backgroundImage = 'url(' + inp.value + ')';
};
div
{
width: 5em;
height: 5em;
}
<input type='text' id='inp' />
<div id='res'>
</div>
It's better practice to use file reader.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#file").change(function(){
var length=this.files.length;
if(!length){
return false;
}
changeBackground(this);
});
});
// Creating the function
function changeBackground(img){
var file = img.files[0];
var imagefile = file.type;
var match= ["image/jpeg","image/png","image/jpg"];
if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2]))){
alert("Invalid File Extension");
}else{
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(img.files[0]);
}
function imageIsLoaded(e) {
$('body').css({ 'background-image': "url(" + e.target.result + ")" });
}
}
</script>
</head>
<body>
<input type="file" name="" id="file" value="Click">
</body>
</html>
You cannot do that purely with client-side because of security reasons.
The moment you upload say an image, the browser gives it a "fakepath" like so:
C:\fakepath\<filename>.png
This is a security implementation of the browser - the browser is protecting you from accessing your disk structure.
Hence when you check the value of your input after uploading, you would get the above fakepath ie. C:\fakepath\<filename>.png. Using this as the background obviously would not work.
Usually to achieve this you need to first store it in a server, then fetch the value from the server and apply the background.
To use a local file, store it in a blob
<head>
<script>
function changeBackground() {
var backgroundFile = document.getElementById("background").files[0];
$('body').css({ 'background-image': "url(" + URL.createObjectURL(backgroundFile) + ")" });
}
</script>
</head>
<body>
<input id="background" type="file" onchange="changeBackground()">
</body>
Related
I'm trying to do basic file input from a text file. I've looked at various posts online and got some of the solution, however, their solution returns a different alert to mine. I want my alert to have the contents of the file in it like theirs does, however mine has a repeat of the file type.
I do not know JQuery, so I would prefer answers in javascript, otherwise I'll struggle to understand.
function fileSelected(el){
if(el.files && el.files[0]){
var f = el.files[0];
if(f){
var FR = new FileReader();
FR.onload = function(e) {
var contents = e.target.result;
console.log(contents.substr(1, contents.indexOf("n")));
alert( "Got the file.\n"
+"name: " + f.name + "\n"
+"type: " + f.type + "\n"
+"size: " + f.size + " bytes \n"
+ "starts with: " + contents.substr(1, contents.indexOf("n"))
);
};
FR.readAsDataURL( el.files[0]);
}
}
}
<html>
<head>
<title>Import File Attempt</title>
<link rel="stylesheet" type="text/css" href ="style.css">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<input type="file" id="fileChoice" onchange="fileSelected(this)">
</body>
</html>
This is the alert that I did get:
Screenshot of my alert
And this is the alert I wanted:
Alert I wanted
Edit:
Thought to add a screenshot of the text file incase that helps:
My text file
If it is a text file, I would suggest reading it using FileReader.readAsText():
function loadfile(event){
var fr=new FileReader();
fr.onload=function(){
txt.value=fr.result;
};
fr.readAsText(event.target.files[0]);
}
textarea{
width: 95%;
height: 300px;
}
<input type="file" accept="text" onchange="loadfile(event)"><br>
<textarea id="txt"></textarea>
(name-type-size worked just fine already, so I left them out)
I do not know if I understood the question well. Do you want to read the contents of the file?
For the .txt file:
console.log(contents.substr(23,));
cut off: data:text/plain;base64, and will display the contents of the file encoded in Base64
check also:
var str = "data:text/plain;base64,VGVzdG93YSB0cmXFm8SHCg==";
console.log (str.replace(/^\S+64,/, ''));
It will also work for other files than txt
Of course, adapt to your needs.
I've got a text file and want to do some find and replace operations to it inside the browser. Unfortunately my coding experience is just really elementary and complete tutorials about building web apps are far too much input at the moment.
Basically I want to upload the file into the browser, then let javascript do the find-and-replace-thing and finally want to download the changed file again.
I've already read about the HTML5 File API and was actually able to load the text file into the browser. But that is where I'm getting lost. In order to split problems up into smaller ones I thought a good next step would be to download the uploaded file again and finally learn how to put the find-and-replace action in between. But I really don't know how to go further and would appreciate any help.
Thanks so far. Benny
document.getElementById('input-file')
.addEventListener('change', getFile)
function getFile(event) {
const input = event.target
if ('files' in input && input.files.length > 0) {
placeFileContent(
document.getElementById('content-target'),
input.files[0])
}
}
function placeFileContent(target, file) {
readFileContent(file).then(content => {
target.value = content
}).catch(error => console.log(error))
}
function readFileContent(file) {
const reader = new FileReader()
return new Promise((resolve, reject) => {
reader.onload = event => resolve(event.target.result)
reader.onerror = error => reject(error)
reader.readAsText(file, "windows-1252")
})
}
<html>
<head>
<meta content="text/html; charset=ANSI" http-equiv="content-type">
<title>Text file manipulator</title>
</head>
<body>
<h1>Text file manipulator</h1>
<p>
<input type="file" id="input-file">
</p>
<p>
<textarea id="content-target" style="width:440px;height:400px;"></textarea>
</p>
</body>
</html>
screenshot of text file uploader
You can add a button and call a function in your JavaScript. Something like
<button onclick="downloadText()">Download</button>
Being the function
function downloadText(){
var content = document.getElementById('content-target').value;
var dl = document.createElement('a');
dl.setAttribute('href', 'data:text/csv;charset=utf-8,' +
encodeURIComponent(content));
dl.setAttribute('download', 'text.txt');
dl.click();
}
Inside the function you should be able to do all the modifications you want. If you give more details, I can help you with the replace section of it, but it should be something like the following:
content.replace(regex, substitute);
More information here
Working CodePen
so I'm trying to set up upload size limit, but it has been unsuccessful.
I have included the code with explanations, please hava a look and I would be very thankfull if you could help me.
More information on wha I needм help with is after the " // "
Here's the code: `
<html>
<p id="check"></p>
//ok so this part of <script> sends the user to "email.html"
<script type="text/javascript">
function getFile(){
document.getElementById("file").click();
}
function sub(obj){
var file = obj.value;
document.myForm.submit();
}
</script>
//here's the code for the button to upload a file (or image in my case)
<form action="e-mail.php" method="post" enctype="multipart/form-data" name="myForm">
<div id="yourBtn" onclick="getFile()">Yes</div>
<div style="text-align: center; overflow: hidden;">
<input type="file" value="upload" id="file" accept="image/*"
onchange="sub(this)"
size="1" style="margin-top: -50px;" "margin-left:-410px;" "-moz-opacity: 0;
"filter:
alpha(opacity=0);" "opacity: 0;" "font-size: 150px;" "height: 100px;">
</div>
</form>
<script>
var attachement = document.getElementById('file');
attachement.onchange = function() {
var file = attachement.files[0];
if (file.size < 1000000) {
function sub(obj){return true; }
//ok so here's the problem,
when I include this code between
'script' the user is not taken
to "e-mail.html" anymore... please help!!!
else { return false;}
}
}
</script>
</html> `
Thanks a lot:)
To go to a different page when the file is too big, you can assign the new URL to document.location. Note that the URL should be absolute (i.e. http://.../email.html).
I suggest to display an error when the file is too big and simply not submit the page. Otherwise, the user will see the new page and believe that everything was all right.
Also note that you need to do the same check on the server because an attacker might just create a POST request from scratch (without using the code from your page) to send files of arbitrary size to your server.
Because the funtion inside of the onchange is not global. It is only available to the onchange.
would would need to change it to
window.sub = function (obj){return true; }
BUT the flaw with this is the user can change the file a second time and submit since you just removed the return false. You could either add it back in on the else OR you can do validation when the form is submitted and not onchange.
How can I read the client's machine/computer name from the browser?
Is it possible using JavaScript and/or ASP.NET?
You can do it with IE 'sometimes' as I have done this for an internal application on an intranet which is IE only. Try the following:
function GetComputerName() {
try {
var network = new ActiveXObject('WScript.Network');
// Show a pop up if it works
alert(network.computerName);
}
catch (e) { }
}
It may or may not require some specific security setting setup in IE as well to allow the browser to access the ActiveX object.
Here is a link to some more info on WScript: More Information
Browser, Operating System, Screen Colors, Screen Resolution, Flash version, and Java Support should all be detectable from JavaScript (and maybe a few more). However, computer name is not possible.
EDIT: Not possible across all browser at least.
Well you could get the ip address using asp.net, then do a reverse DNS lookup on the ip to get the hostname.
From the ASP.NET Developer's cookbook ... Performing a Reverse-DNS Lookup.
It is not possible to get the users computer name with Javascript. You can get all details about the browser and network. But not more than that.
Like some one answered in one of the previous question today.
I already did a favor of visiting your website, May be I will return or refer other friends.. I also told you where I am and what OS, Browser and screen resolution I use Why do you want to know the color of my underwear? ;-)
You cannot do it using asp.net as well.
Try getting the client computer name in Mozilla Firefox by using the code given below.
netscape.security.PrivilegeManager.enablePrivilege( 'UniversalXPConnect' );
var dnsComp = Components.classes["#mozilla.org/network/dns-service;1"];
var dnsSvc = dnsComp.getService(Components.interfaces.nsIDNSService);
var compName = dnsSvc.myHostName;
Also, the same piece of code can be put as an extension, and it can called from your web page.
Please find the sample code below.
Extension code:
var myExtension = {
myListener: function(evt) {
//netscape.security.PrivilegeManager.enablePrivilege( 'UniversalXPConnect' );
var dnsComp = Components.classes["#mozilla.org/network/dns-service;1"];
var dnsSvc = dnsComp.getService(Components.interfaces.nsIDNSService);
var compName = dnsSvc.myHostName;
content.document.getElementById("compname").value = compName ;
}
}
document.addEventListener("MyExtensionEvent", function(e) { myExtension.myListener(e); }, false, true); //this event will raised from the webpage
Webpage Code:
<html>
<body onload = "load()">
<script>
function showcomp()
{
alert("your computer name is " + document.getElementById("compname").value);
}
function load()
{
//var element = document.createElement("MyExtensionDataElement");
//element.setAttribute("attribute1", "foobar");
//element.setAttribute("attribute2", "hello world");
//document.documentElement.appendChild(element);
var evt = document.createEvent("Events");
evt.initEvent("MyExtensionEvent", true, false);
//element.dispatchEvent(evt);
document.getElementById("compname").dispatchEvent(evt); //this raises the MyExtensionEvent event , which assigns the client computer name to the hidden variable.
}
</script>
<form name="login_form" id="login_form">
<input type = "text" name = "txtname" id = "txtnamee" tabindex = "1"/>
<input type="hidden" name="compname" value="" id = "compname" />
<input type = "button" onclick = "showcomp()" tabindex = "2"/>
</form>
</body>
</html>
There is no way to do so, as JavaScript does not have an access to computer name, file system and other local info. Security is the main purpose.
No this data is not exposed. The only data that is available is what is exposed through the HTTP request which might include their OS and other such information. But certainly not machine name.
<html>
<body onload = "load()">
<script>
function load(){
try {
var ax = new ActiveXObject("WScript.Network");
alert('User: ' + ax.UserName );
alert('Computer: ' + ax.ComputerName);
}
catch (e) {
document.write('Permission to access computer name is denied' + '<br />');
}
}
</script>
</body>
</html>
There is some infos to parse into the webRTC header.
var p = new window.RTCPeerConnection();
p.createDataChannel(null);
p.createOffer().then((d) => p.setLocalDescription(d))
p.onicecandidate = (e) => console.log(p.localDescription)
An updated version from Kelsey :
$(function GetInfo() {
var network = new ActiveXObject('WScript.Network');
alert('User ID : ' + network.UserName + '\nComputer Name : ' + network.ComputerName + '\nDomain Name : ' + network.UserDomain);
document.getElementById('<%= currUserID.ClientID %>').value = network.UserName;
document.getElementById('<%= currMachineName.ClientID %>').value = network.ComputerName;
document.getElementById('<%= currMachineDOmain.ClientID %>').value = network.UserDomain;
});
To store the value, add these control :
<asp:HiddenField ID="currUserID" runat="server" /> <asp:HiddenField ID="currMachineName" runat="server" /> <asp:HiddenField ID="currMachineDOmain" runat="server" />
Where you also can calling it from behind like this :
Page.ClientScript.RegisterStartupScript(this.GetType(), "MachineInfo", "GetInfo();", true);
Erm is there any reason why you can't just use the HttpRequest? This would be on the server side but you could pass it to the javascript if you needed to?
Page.Request.UserHostName
HttpRequest.UserHostName
The one problem with this is it would only really work in an Intranet environment otherwise it would just end up picking up the users Router or Proxy address...
I have 2 HTML pages, send.html and receive.html
In each page I have a textield. The thing that I'm trying to do is whenever the "value" of the textfield in the send.html changes, automatically parse the data to the textfield value of the receive.html. When I say automatically I mean without the need of a button or reloading the pages.
To sum up.. I have this textfiled in the send.html
<input type="text" id="send" size="25" value="Val1">
And this text field in the receive.html
<input type="text" id="receive" size="25" value="Val2">
I want to "monitor" somehow the Val1, and if it changes I want Val2=Val1
For my purpose I cant use jquery.
Is that possible?
I think you are missing a big picture. Data sending and receiving needs some server side interaction like using PHP, ASP, JSP, Python etc., unless you are ok with cookies.
When you update a field in one age, that data needs to go the server somehow for another page to catch. Either way, the way you want it to go automatic is not possible right now. However, I will provide a solution of how you can do this using jQuery and PHP. But if you want?
Update
So, it seems cookies is the only option. Follow the following steps
Create a new file cookie.js and place the following code inside
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
Next, create two html file "test1.html" and "test2.html" with this markup
<html>
<head>
<script src="cookie.js"></script>
</head>
<body>
<input type="text" id="text1" name="text1" />
</body>
</html>
Now, on test1.html add the following script on the head
<script>
window.onload = function() {
document.getElementById("text1").onchange = function() {
// ^ use onkeyup if you want this to occur as you type
setCookie("shared", this.value, 1);
alert('oK, val changed so lets check it');
};
};
</script>
On Test2.html add the following Script on the head
<script>
var checkandupdate = function() {
var shared = getCookie("shared");
if(shared) {
document.getElementById("text1").value = shared;
}
};
window.onload = function() {
int = setInterval("checkandupdate()",1000);
};
</script>
Now
Open both pages
Go to test1.html and type something then press tab to get the alert message.
Open the test2.html, it should be update within 1 second
After the demo works, Update the field names as you need
Enjoy ;)
In your second HTML page , let's say we call it like page-2.html?send=xyz when the value is being changed , you add the following JS Code :
function getQueryString() {
var result = {}, queryString = location.search.substring(1),
re = /([^&=]+)=([^&]*)/g, m;
while (m = re.exec(queryString)) {
result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
return result;
}
var sendValue= getQueryString()["send"];
document.getElementById("receive").value=sendValue;
if you want to use without cookie for improving the performance.. you can use this library it uses window.name to carry the values.. however it will not work if the user opens in new tab.. still it is good.. only thing is you should handle new tab situation..
Hope this helps.. especially it will help if it is a html based front end..