JavaScript Automatically Save Image File to Folder - javascript

How can I automatically save an image from canvas into a folder? I am using the
signature_pad-1.5.2 from szimek (link). Here is what I have tried so far:
HTML CANVAS
<div id="signature-pad" class="m-signature-pad">
<div class="m-signature-pad--body">
<canvas></canvas>
</div>
<div class="m-signature-pad--footer">
<div class="description">Signature</div>
<button type="button" class="button clear" data-action="clear">Clear</button>
<button type="button" class="button save" data-action="save">Save</button>
</div>
</div>
<script src="js/signature_pad.js"></script>
<script src="js/app.js"></script>
The signature_pad.js is for drawing in the canvas. Here is the content of my app.js from signature_pad-1.5.2 (I modified it a little):
app.js
var wrapper = document.getElementById("signature-pad"),
clearButton = wrapper.querySelector("[data-action=clear]"),
saveButton = wrapper.querySelector("[data-action=save]"),
canvas = wrapper.querySelector("canvas"),
signaturePad;
saveButton.addEventListener("click", function (event) {
if (signaturePad.isEmpty()) {
alert("Please provide signature first.");
} else {
newfolder = myObject.CreateFolder ("C:\\xampp\\htdocs\\signature\\resources\\sigs");
alert();
saveButton.href = signaturePad.toDataURL();
saveButton.download = 'image.png';
}
});
I am trying to save the image.png file to newFolder when I click the save button. Thanks

There is no way for javascript to access the filesystem, this is due to security concerns. You can store the image data as a string in a lot of places though, such as browser storage. Luckily for you it looks as though you're trying to store it in a web server's folder!
The best thing for you to do here is to make a script on the server that you want to store the image on. That script will accept a file POST request and store it in a server folder somewhere. This can be written in php for example.
Once you have that server-side script, make an AJAX request from the client (from the javascript) with the image data to that server script.
I would provide code samples and a more in-depth explanation, but unfortunately you haven't provided any real info about your tech stack and what exactly you're trying to accomplish. Good luck!

Related

JavaScript - How to download image from fetched in network [duplicate]

This is crazy but I don't know how to do this, and because of how common the words are, it's hard to find what I need on search engines. I'm thinking this should be an easy one to answer.
I want a simple file download, that would do the same as this:
Download!
But I want to use an HTML button, e.g. either of these:
<input type="button" value="Download!">
<button>Download!</button>
Likewise, is it possible to trigger a simple download via JavaScript?
$("#fileRequest").click(function(){ /* code to download? */ });
I'm definitely not looking for a way to create an anchor that looks like a button, use any back-end scripts, or mess with server headers or mime types.
You can trigger a download with the HTML5 download attribute.
Download
Where:
path_to_file is a path that resolves to an URL on the same origin. That means the page and the file must share the same domain, subdomain, protocol (HTTP vs. HTTPS), and port (if specified). Exceptions are blob: and data: (which always work), and file: (which never works).
proposed_file_name is the filename to save to. If it is blank, the browser defaults to the file's name.
Documentation: MDN, HTML Standard on downloading, HTML Standard on download, CanIUse
For the button you can do
<form method="get" action="file.doc">
<button type="submit">Download!</button>
</form>
HTML:
<button type="submit" onclick="window.open('file.doc')">Download!</button>
A simple JS solution:
function download(url) {
const a = document.createElement('a')
a.href = url
a.download = url.split('/').pop()
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
}
With jQuery:
$("#fileRequest").click(function() {
// hope the server sets Content-Disposition: attachment!
window.location = 'file.doc';
});
You can do it with "trick" with invisible iframe. When you set "src" to it, browser reacts as if you would click a link with the same "href". As opposite to solution with form, it enables you to embed additional logic, for example activating download after timeout, when some conditions are met etc.
It is also very silient, there's no blinking new window/tab like when using window.open.
HTML:
<iframe id="invisible" style="display:none;"></iframe>
Javascript:
function download() {
var iframe = document.getElementById('invisible');
iframe.src = "file.doc";
}
Bootstrap Version
<a class="btn btn-danger" role="button" href="path_to_file"
download="proposed_file_name">
Download
</a>
Documented in Bootstrap 4 docs, and works in Bootstrap 3 as well.
I think this is the solution you were looking for
<button type="submit" onclick="window.location.href='file.doc'">Download!</button>
I hade a case where my Javascript generated a CSV file. Since there is no remote URL to download it I use the following implementation.
downloadCSV: function(data){
var MIME_TYPE = "text/csv";
var blob = new Blob([data], {type: MIME_TYPE});
window.location.href = window.URL.createObjectURL(blob);
}
You can hide the download link and make the button click it.
<button onclick="document.getElementById('link').click()">Download!</button>
<a id="link" href="file.doc" download hidden></a>
What about:
<input type="button" value="Download Now!" onclick="window.location = 'file.doc';">
In my testing the following works for all file types and browsers as long as you use a relative link:
<button>Download 2</button>
/assets/hello.txt is just a relative path on my site. Change it to your own relative path.
my_file.txt is the name you want the file to be called when it is downloaded.
Explanation
I noticed there were comments under a lot of the answers that said the browser would just try to open the file itself rather than downloading it depending on the file type. I discovered this to be true.
I made two buttons to test it out using two different methods:
<button onclick="window.location.href='/assets/hello.txt';">Download 1</button>
<button>Download 2</button>
Notes:
Button 1 opened the text file in a new browser tab. However, Button 1 would download the file for file types that it couldn't open itself (for example, .apk files).
Button 2 downloaded the text file. However, Button 2 only downloaded the file if the path was relative. When I changed the path to an absolute path, then the browser opened it in a new tab.
I tested this on Firefox, Safari, and Chrome.
Hello I just include the word 'download' and works well.
<a href="file.pdf" download>Download</a>
So in javascript you can use the follow:
function onStartedDownload(id) {
console.log(`Started downloading: ${id}`);
}
function onFailed(error) {
console.log(`Download failed: ${error}`);
}
var downloadUrl = "https://example.org/image.png";
var downloading = browser.downloads.download({
url : downloadUrl,
filename : 'my-image-again.png',
conflictAction : 'uniquify'
});
downloading.then(onStartedDownload, onFailed);
If your looking for a vanilla JavaScript (no jQuery) solution and without using the HTML5 attribute you could try this.
const download = document.getElementById("fileRequest");
download.addEventListener('click', request);
function request() {
window.location = 'document.docx';
}
.dwnld-cta {
border-radius: 15px 15px;
width: 100px;
line-height: 22px
}
<h1>Download File</h1>
<button id="fileRequest" class="dwnld-cta">Download</button>
<button>Download!</button>
This will download the file as .doc file extension is not supported to be opened in browser.
One of the simplest way for button and the text-decoration will help to alter or to remove the text decoration of the link.
Anywhere between your <body> and </body> tags, put in a button using the below code:
<button>
<a href="file.doc" download>Click to Download!</a>
</button>
This is sure to work!
all you need to do is add Download after the file name which you have entered:
Before:
Download!
After
<a href="file.doc" Download >Download!</a>
Make sure the download is written with a capital letter otherwise it's not gonna work.
This is what finally worked for me since the file to be downloaded was determined when the page is loaded.
JS to update the form's action attribute:
function setFormAction() {
document.getElementById("myDownloadButtonForm").action = //some code to get the filename;
}
Calling JS to update the form's action attribute:
<body onLoad="setFormAction();">
Form tag with the submit button:
<form method="get" id="myDownloadButtonForm" action="">
Click to open document:
<button type="submit">Open Document</button>
</form>
The following did NOT work:
<form method="get" id="myDownloadButtonForm" action="javascript:someFunctionToReturnFileName();">
If you can't use form, another approach with downloadjs fit nice. Downloadjs use blob and html 5 file API under the hood:
<div onClick=(()=>{downloadjs(url, filename)})/>
*it's jsx/react syntax, but can be used in pure html
Not really an answer to the original question but it may help others which face similar situations as myself.
If the file you want to download is not hosted on the same origin but you want to be able to download it, you can do that with the Content-Disposition header. Make sure the server includes the header when responding to requests of the file.
Setting a value like
Content-Disposition: attachment will ensure that the file will be downloaded instead of viewed in the browser.
A simple Download pointing to your file should download it in this case.
If you want
Download
for the ability to download files that would be rendered by the browser otherwise, But still want a neat javascript function to use in a button; you can have an invisible link in html and click it in javascript.
function download_file() {
document.getElementById("my_download").click()
}
<a id="my_download" href="path_to_file" download="file_name" style="display:none;"></a>
<button onClick="download_file()">Download!!!</button>
Another way of doing in case you have a complex URL such as file.doc?foo=bar&jon=doe is to add hidden field inside the form
<form method="get" action="file.doc">
<input type="hidden" name="foo" value="bar" />
<input type="hidden" name="john" value="doe" />
<button type="submit">Download Now</button>
</form>
inspired on #Cfreak answer which is not complete
The solution I have come up with is that you can use download attribute in anchor tag but it will only work if your html file is on the server. but you may have a question like while designing a simple html page how can we check that for that you can use VS code live server or bracket live server and you will see your download attribute will work but if you will try to open it simply by just double clicking html page it open the file instead of downloading it.
conclusion: attribute download in anchor tag only works if your html file is no server.
For me ading button instead of anchor text works really well.
<button>Download!</button>
It might not be ok by most rules, but it looks pretty good.
If you use the <a> tag, do not forget to use the entire url which leads to the file -- i.e.:
Download

How to syntetically create a File Upload event to pass to the onChange handler

I have an HTML page with a File Upload element like this:
<div>
<fieldset>
<legend>Upload your File</legend>
<input type="file" id="fileUpload" name="File Upload" accept=".txt"/>
</fieldset>
</div>
and a script part like this:
<script src="myuploadscript.js"></script> <!-- defines myuploadfunc() -->
<script type="text/javascript">
$(document).ready(function() {
$("#fileUpload").on("change", myuploadfunc)
})
</script>
For developing the function myuploadfunc() I would like it that I don't need to click the Browse button and select the file mytext.txt to run the function, but rather create a synthetic upload event uploadfile_event which I can pass (in the document ready function) straight to myuploadfunc. Therefor on browser reload the upload functionality would run automatically. :-)
So for development the modified documnet ready part would look like this:
<script type="text/javascript">
$(document).ready(function() {
var uploadfile_event = ... // something specifying the file /path/to/mytext.txt
myuploadfunc(uploadfile_event)
})
</script>
But how do I create uploadfile_event? And in particular how do I specify the custom information of the file to upload with its (client-side) path?
Indeed there is a way to achieve your demand, checkout the FileSystem API, which is able to access OS's file system without file selection.
As you see, the compatibility of this API is pretty poor since it is not encouraged. You should take it with a grain of salt when using it.

How to change a HTML-element to the selection of a File-Dialog?

I am currently working on a python program that uses a html/css interface which is connected through eel. It requires the user to load a file to analyze. In order to show the user on the User interface which file was selected, I want to show the name of the file (or the path) after the selection process is done.
Since I am new to this, I found a simple filedialog on the internet (probably somewhere here on Stackoverflow) that uses JQuery to select the path to a file. The selection works fine and my program can work with that information if the file that is being selected is located in the same folder as the html file, as this circumvents fakepath errors and I do not know a way around it.
I want to display the selected path underneath the button once it has been selected. However, in the current configuration it displays [object object] right after clicking the "Browserino" button and not the selected path or (ideally) the selected filename.
The HTML document contains:
<div class="col">
<button id="button" class="btn btn-primary" onclick="clicked();">Browserino</button>
<input id="file-input" type="file" name="name" style="display: none;" />
<small id="pathway" class="form-text text-muted">invisible</small>
</div>
And the main.js has this function to work with:
function clicked(){
var path = String($('#file-input').trigger('click'));
document.getElementById('pathway').innerHTML = path;
document.getElementById('pathway').style.visibility = 'visible';
}
I have also tried the follwing in the main.js, but it does not do the trick for me:
function clicked(){
String($('#file-input').trigger('click'));
var file_input = document.getElementById('file-input').value;
var filepath = file_input.replace(/^.*[\\\/]/, '');
document.getElementById('pathway').innerHTML = filepath;
}
Thanks for all the comments before, I hope this edit helps clarify the problem. Any help is appreciated. Thx.

Sending Pdf, created with html2pdf, via Mail

I'm trying to send a document using eKoopmans html2pdf (new-api-branch) script via email. But since I'm not a trained programmer, I'm having a couple of problems with it.
Here is my code so far
<head>
<!-- Stuff that goes here -->
<script src="opt/html2pdf-new-api/dist/html2pdf.bundle.min.js"></script>
<script>
$(document).ready(function(){
$("#cmd").click(function(){
var signaturefilename = $('#auftragsnummer').val();
var element = document.getElementById('PDFcontent');
var opt ={
filename: signaturefilename+'.pdf',
image: { type: 'jpeg', quality: 1 },
}
html2pdf().from(element).set(opt).save();
});
});
</script>
</head>
<body>
<div class="container" id="PDFcontent">
<!-- Contents that should be converted to pdf -->
</div>
</body>
I can save the file, using the value of an input field as filename, without any problems. Everything I need is in the PDF and it displays fine.
As I've read in one of the issues here, it is possible to get that PDF data and pass it to phpmailer. But I have to be honest here, I have no clue on how to do that. I tried to do
html2pdf().from(element).set(opt).toDataURL();
instead, but that just gave me an error.
What I want to do in the end is as follows. I want to create that PDF and attach it to an email. That email should also have the value of the field with the id="auftragsnummer" + some text as subject.
I think I would need to get some kind of string, store in a var and pass that to phpmailer. I probably need to decode it back inside the php-script, but as I've said, my knowledge is limited...
If someone could help me, on how to attach that PDF to phpmailer, or somehow save it on the server, that would be highly appreciated.
Thanks in advance for your help. Best regards

html form - upload file to storage without php

All the exmaple I saw was with a form that redirect to file upload.php. I want to do a little differnt.
I have a form and there I have :
<input type="file" name="img1" id="img1">
and in the end of the form:
<button type="button" class="submit-button" onclick="signUp()"/> signup </button>
I want in the signUp() function to store the file in my storage and get url to thiss file.
What I did so far is :
var fileUploadControl = $("#img1")[0];
if (fileUploadControl.files.length > 0) {
var file = fileUploadControl.files[0];
......................
}
but I don't know how to continue. thanks!
It is not possible to store data/file without using a server side language(like PHP,C#,...).
Else anyone could save files to your server and that is something you don't want!
I recommenced to use a combination of HTML and PHP! You will find a good documentation on http://www.php.net/manual/en/features.file-upload.post-method.php

Categories