File browsing is not working Chrome browser - javascript

I am trying to browse XLS file and processing.
First time I am browsing file and processing ,having some errors in file its showing.
I am clearing errors and selected file .Re-corrected the error file.
I am trying to browse re=corrected file (same file whatever I browse first time),but its not working.Its not reading file in Chrome.
This functionality is working fine in Mozilla.
<input type="button" value="browse"/>
<input type="file" id="manifestFileId" name="manifestFile" class="file_input_hidden createPageBrowseButton" onchange="alertFilename()"/>
<input type="button" class="clearFileInput" id="resetform" name = "reset" value="clear" />

To reload the file you first need to clear the existing value.
document.getElementById('manifestFileId').value = null;
After this, you should be able to reselect the updated file.

Related

Download file returned after uploading a file : An AJAX file converter

I'm programming a PHP function that encrypts a file using a specific key. I want the user to upload his file using the "browse..." window then get the "save as" window as a result after the php encrypting.
I'm working in full AJAX so my upload method uses a hidden form and a hidden iframe to handle the upload request.
Javascript Part :
<script>
$("#encryptFileButton").button().click(clickEncryptFile);
function clickEncryptFile() {
if (!jQuery.browser.msie) {
$("#encryptFileBrowse").click();
} else {... not the matter of the question ...}
}
function encryptFileBrowseChange() {
$("#uploadAttachmentForm").submit();
}
</script>
The nice visible button
<button id="encryptFileButton" type="button" class="ui-..." role="button">Encrypt Now</button>
The hidden part
<form action="https://web.com/encryptPHP" id="uploadAttachmentForm" target="uploadTarget" style="display:none" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<input type="file" name="encryptFileBrowse" id="encryptFileBrowse" onchange="encryptFileBrowseChange()">
</form>
<iframe id="uploadTarget" name="uploadTarget" src=""></iframe>
Now on the server side, the encryptPHP does the job and returns the encrypted file with all the required HTTP headers. But the browser does not open the "save as window"
Here is the Chrome inspector of the request
Can you help me to fill the download part of this problem ?
I wouldn't like using a temporary file on the server to be stateless and prevent orphan files when browser is interrupted. I'd really like to make this with only one query.
In the server response, Content-disposition is inline, it must be content-disposition: attachment to get the "save as " popup.
I don't delete my question as the code example is pretty and usefull.
Uploading and downloading in only one request is nice.

Use Fluentlenium to upload a file in dropzone.js

I'm looking to write a test to upload a file using Fluentlenium and DropZone.js (http://www.dropzonejs.com/). Dropzone.js works in a modal and then you can drag and drop or upload the normal way.
As soon as you click to upload the test crashes because your no longer in the browser.
I've found many posts getting this to work in Selenium using things like:
WebElement fileInput = driver.findElement(By.xpath("//input[#type='file']"));
fileInput.sendKeys("C:/path/to/file.jpg");
I however cannot sendKeys to anything because their isn't even an input type="file" when using DropZone.js.
The only input types I'm seeing are all type hidden.
<input type="hidden" name="key" value="temp/${filename}">
<input type="hidden" name="AWSAccessKeyId" value="secret">
<input type="hidden" name="acl" value="private">
<input type="hidden" name="success_action_redirect" value="">
<input type="hidden" name="policy" value="secret=">
<input type="hidden" name="signature" value="secret">
<input type="hidden" name="Content-Type" value="application">
We're also using Amazon Web Server to upload the documents too, it seems like everything is working off the below script:
<script id="hiddenKeyPairs" type="text/javascript">
var hiddenKeyPairs = {
key: 'temp/${filename}',
AWSAccessKeyId: 'secret',
acl: 'private',
"success_action_redirect": '',
policy: 'secret',
signature: 'secret/secret',
"Content-Type": 'application'
};
var formAction = 'https://secret.com/';
</script>
Which is located on my page.
I'm not seeing anything helpful on https://github.com/FluentLenium/FluentLenium#driver for this.
Do I need to somehow send the file to the key hash in the above script?
Any thoughts?
I'm not sure about the AWS part but I've a similar question about file upload (Programmatically upload / add file via Dropzone e.g. by Selenium), and some potential solutions. I feel they are not very robust, but basically:
Approach 1: Use Java Robot to simulate the GUI actions -
// this opens the file browser window
driver.findElement(By.id("uploadDropzone")).click();
// put the file path in clipboard, paste (C-V) to the window, enter.
StringSelection ss = new StringSelection("some file path");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
Robot robot = new Robot();
Thread.sleep(2000);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
Thread.sleep(5000); // need some wait for GUI action to work...
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER)
Approach 2: Do all in code (hacky...) - yes there is a file input element, but only defined in Dropzone.js itself, which can be selected with $(".dz-hidden-input"). But you also have to make it visible (as Selenium can only act on visible elements), then can call sendKeys on it. And after that, again in Javascript, retrieve the File object from that element, then pass to addFile(file) on the Dropzone object.

Get value of file upload to a hidden text box

I'm trying to get the value or file path from a html file upload control to a hidden input text box as soon as I select a file.
<input type="file" name="some_name" id="file" />
<input type="text" name="text_name" id="abc" style="display:none;" value=""/>
and my script looks like:
$('#file').live('change', function(){ alert("yes"); });
so I get the alert box but I would like to change the value of the hidden input field to the path of the file I select. Any help to solve this problem is highly appreciated.
Usually you get an element's value with $('#elementId').val(), but in the case of a an <input type="file"> you can't, because of security restrictions. There is no way to know the local file path (at least none that works consistently on all browsers).
To get the file path of an upload control <input type='file'> you can do the following:
var value = $('#elementID').val();
var value = value.substr(value.lastIndexOf('\\') + 1);
This will trim off any file path that comes before the filename. In the case of IE and Firefox the full file path and in the case of Chrome and Safari the C:\Fake Path.
See the associated jsfiddle:
Fiddle
Does it work ?
$('#file').change(function() {
$('#abc').val($(this).val());
});
I guess it doesn't: see bfavaretto answer.

How to trigger a file download when clicking an HTML button or JavaScript

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

Get files from input.files instead of value on submit

I have following problem. I have input field in form, type of file:
<FORM action="http://server.com/cgi/handle"
enctype="multipart/form-data"
method="post">
<P>
What is your name? <INPUT type="text" name="submit-name"><BR>
What files are you sending? <INPUT type="file" name="files"><BR>
<INPUT type="submit" value="Send"> <INPUT type="reset">
</FORM>
I am setting using JavaScript also files property of this input and I want this input on submit of form send the file property instead of his value. Is it possible to do so?
var data = e.dataTransfer;
var input = dojo.byId(inputName);
var file = data.files[i];
input.files[0] = file;
data is a datatransfer object, I am getting files from there.
I know, it will be possible only in few browsers, I dont care. I just need to get it working at least in FF.
So if I understand you correctly you drop some files and you want to populate a file input object
I see a drop example here http://help.dottoro.com/ljslrhdh.php
but to populate the file field you will need a pretty heavy privilege change using a signed script - UniversalFileRead is probably the one you need

Categories

Resources