I want to write a browser add-on that automatically upload file on the page. So this will be done in pure Javascript.
This is what I have / know:
input#someId of the file upload input
File name and location in the computer
I am trying to "hardcode" in the console for now as a "Proof of Concept" but I cannot get it to work.
I have tried these two methods:
inputElement.click() as inputElement is the querySelector of that input.
Use initMouseEvent from what's the equivalent of jquery's 'trigger' method without jquery? but gave me error Uncaught TypeError: Cannot read property 'dispatchEvent' of null
So my questions are:
How to trigger click input of file upload element?
Better: how to process the upload completely? Basically pass the filename+location for upload to start (like when user clicks OK to open the file from the dialog)
UPDATE 1:
I was reading this http://www.thecssninja.com/javascript/fileapi
Maybe uploading file from File System is not possible. How about these alternatives:
We can grab a file from url (http)
The file is just image and in Javascript memory (base64)
Anyone of the above should be OK if they can be automatically upload and bypass the dialog box and search the file via local File System. I am thinking what if the image DOM or even canvas can be just dragged?
As people commented, you cannot do that. For security reasons, you have absolutely no access to programmatic fill an file input. Think about it, some dude could add a simple script to steal files from your computer and you wouldn't even know!
As far as I know, can't be done.
Related
<img class='preview' src='preview.png'>
This is an input for image upload:
<input type='file' class='img-upload' accept='image/*'>
When I clicked on the preview image(<img class='preview' src='preview.png'>), I have to change the value of the file input (<input type='file' class='img-upload' accept='image/*'>). The value of the file input should be the preview image.
Short answer: you cannot.
Long answer: The problem is that the file inputs are very sandbox'ed and will not allow user scripts to change their value. The goal is to make sure the user needs to click and acknowledge that he is sending a file from his computer.
Now, the user cannot send the image he clicked on mostly because it is not on his computer (well, technically yes, but even then he would need to know where it is stored and choose it by manually going over the folder). Another thing is, why would you want him to send over a file that you have served him? You could simply get the name of the file or an ID of any sort and use that internally.
Let's take the example of an user avatar. The user gets the possibility to pick between 10 different "preset" pictures, or to upload his own. What you'd do is have 2 form fields, one for the uploaded picture and one for the chosen preset. On server side you would see if the user uploaded a picture, and use that one. If not, use the picture he chose from your server.
I hope I got your question right...
EDIT: If you really, really, really needed to upload the displayed picture, you could get the image data (with ajax I guess), store it into a Blob and send it for upload.
But that has some serious drawbacks. And I think you'll be limited by crossdomain policies so basically you'll only be able to access files that your server can access directly...
Even if you got all that covered, it would be a painfully slow process for the user while all that is required is just sending the name of the picture and the server does the rest.
input type="file" can only be set by the user. Not by a script (not HTML, nor javascript, ...).
Every exe on a windows pc has the capacity to access your files. Including renaming, deleting, encrypting, ... them. For example that's what Wannacry (randsomware) does.
(similar for Mac and Linux, I guess)
A webbrowser is an executable, thus has all those capacities. For security reasons most of these features are turned off, on purpose.
Long ago I wrote a program in C++ (or C#, not sure), with Visual Studio. VS has a webbrowser component. The purpose was to upload multiple albums of photos to a website, but the exe on my pc did have the capacity to use a script to set the input type="file".
So my program could read all subfolders, find all images, automatically upload them, and then the php server saved the albums/images.
In order to stop people like you and me from doing these kind of things, real webbrowsers disabled all these abilities.
I have a file structure on a web page, and look for a solution for the following scenario:
The chosen file should be downloaded in browser cache and opened (if it's an excel document, open with excel, etc.).
Now when the user changes the file, it should be detected and the file should be uploaded again.
Is this even possible with JavaScript?
If yes, where do I store the file (temporary internet folder?) and how do I detect the changes?
The only way for this to work you would need to have the user select the downloaded file, and then check for modification.
HTML
<label for="excelFile">Select the excel file: </label><input type="file" id="excelFile" />
JS
//Change event to detect when the user has selected a file
document.querySelector("#excelFile").addEventListener("change",function(e){
//get the selected file
var file = this.files[0];
//get the last modified date
var lastModified = file.lastModified;
//check lastModified against stored lastModified
//this assumes you store the last mod in localStorage
if(localStorage['excelLastMod'] < lastModified){
//It has modified update last mod
localStorage['excelLastMod'] = lastModified;
//do upload
}
});
If you know your user is using Chrome you can use Chrome's FileSystem api
The way you describe it: No, that is not possible in JavaScript.
It sounds like you want an FTP client.
When the user changes the file, it should be detected and the file should be uploaded again.
That is not possible due to JS having almost no access to the file system.
The only way you can access a file at all is by requesting the user to select one, see:
How to open a local disk file with Javascript?
So the most you could do would be:
File is downloaded.
Based on browser & settings, file may be opened automatically, or not.
User is presented with a file selection dialog that they can use when they are done editing.
Compare selected file to file on server and upload if changed.
After downloading a file, you have no control over it.
For applications that have a protocol registered (such a steam://, for example), you might be able to request the URL being opened in a program, but that would require an if per file type/program.
Detecting file changes is not at all possible (because you have no access to the file), and uploading again requires the user to select the file manually, using a file dialog.
Thanks for your help and ideas. I saw a software (https://www.group-office.com/) which includes this function so there has to be way to do it.
New Idea, using chrome filesystem api (#Siguza already said it):
Create file from servers database on users local filesystem with filesystem api
open file locally (should work with filesystem:http://www.example.com/persistent/info.txt, or?)
poll last changes of file every x seconds
if change detected, upload file back to servers database
I saw some problems with excel locking the files Check if file has changed using HTML5 File API
but except of that this should work, shouldn't it?
I'm working on an HTML/javascript app intended to be run locally.
When dealing with img tags, it is possible to set the src attribute to a file name with a relative path and thereby quickly and easily load an image from the app's directory. I would like to use a similar method to retrieve a text file from the app's directory.
I have used TideSDK, but it is less lightweight. And I am aware of HTTP requests, but if I remember correctly only Firefox has taken kindly to my use of this for local file access (although accessing local images with src does not appear to be an issue). I am also aware of the FileReader object; however, my interface requires that I load a file based on the file name and not based on a file-browser selection as with <input type="file">.
Is there some way of accomplishing this type of file access, or am I stuck with the methods mentioned above?
The browser will not permit you to access files like that but you can make javascript files instead of text files like this:
text1.js:
document.write('This is the text I want to show in here.'); //this is the content of the javascript file
Now call it anywhere you like:
<script type="text/javascript" src="text1.js"></script>
There are too many security issues (restrictions) within browsers making many local web-apps impossible to implement so my solution to a similar problem was to move out of browsers and into node-webkit which combines Chromium + Node.js + your scripts, into an executable with full disk I/O.
http://nwjs.io/
[edit] I'm sorry I thought you wanted to do this with TideSDK, I'll let my answer in case you want to give another try to TideSDK [/edit]
I'm not sure if it's what you're looking for but I will try to explain my case.
I've an application which allow the user to save the state of his progress. To do this, I allow him to select a folder, enter a filename and write this file. When the user open the app, he can open the saved file, and get back his progress. So I assume this enhancement is similar of what you are looking for.
In my case, I use the native File Select to allow the user to select a specific save (I'm using CoffeeScript) :
Ti.UI.currentWindow.openFileChooserDialog(_fileSelected, {
title: 'Select a file'
path: Ti.Filesystem.getDocumentsDirectory().nativePath()
multiple: false
})
(related doc http://tidesdk.multipart.net/docs/user-dev/generated/#!/api/Ti.UI.UserWindow-method-openFileChooserDialog)
When this step is done I will open the selected file :
if !filePath?
fileToLoad = Ti.Filesystem.getFile(scope.fileSelected.nativePath())
else
fileToLoad = Ti.Filesystem.getFile(filePath)
data = Ti.JSON.parse(fileToLoad.read())
(related doc http://tidesdk.multipart.net/docs/user-dev/generated/#!/api/Ti.Filesystem)
Please note that those snippets are copy/paste from my project and they will not work without the rest of my code but I think it's enough to illustrate you how I manage to open a file, and read his content.
In this case I'm using Ti.JSON.parse because there is only javascript object in these files but in your case you can just get the content. The openFileChooserDialog isn't mandatory, if you already know the file name, or if you get it from another way you can use Ti.Filesystem in your own way.
I am adding a check to verify the size of the file imported in my web application. If the file size is greater than 4 MB i need to show a confirmation pop, whether a user is sure to upload the file. If user selects yes the default functionality occurs else upload is cancelled.
I am trying to open a confirmation pop up from server side using
Page.ClientScript.RegisterStartupScript(typeof(NewDocument), "ValidateFileSize", "<script>ValidateFileSize()</script>");
Where ValidateFileSize() is a JavaScript function that shows the confirmation box.
But the problem is, the control of the page at server side moves ahead before I set the result of the confirmation pop up using hidden variable and use it in 'if-else' condition. Therefore, i am unable to read the value of the hidden variable and skipping the uploading code at server side.
I am using the concept of hidden variable as in javascript element.files.size does not work in IE8.
Could anyone suggest a better approach or solution to this.
Or the only solution is using .aspx page as a popup?
first of all your question is not clear, i hope your requirement is to check file size at client side. but you question indicating that you are looking for how to open popup in javascript.
any way, when comes to your question,
once control goes to server side then file upload control will be refreshed, so better check file size completely in javascript instead of calling script method from server side.
below are some urls for you reference.
Get file size before uploading
JavaScript file upload size validation
Applying javascript to check file size and extension
You can use a literal control and set its html to script.
e.g.
<asp:Literal ID="LiteralText" runat="server" Text=""></asp:Literal>
and then from your server side set the Text property as below
if(FILE SIZE IS > 4MB)
{
LiteralText.Text = "<script>ValidateFileSize()</script>";
}
else{
//UPLOAD FILE LOGIC HERE
}
I am trying to allow users to upload pictures to the server.
I am trying to create a similar system to any website that has an 'attach' file or 'upload image' feature. All I need is to get the full path of the file select by the file dialog.
I tried using this for the file dialog with no success:
<input type="file">
This method does not provide the full file path, due to security reasons. My question is how can I create a similar input dialog to websites like tinypic, photobucket, etc.. that can help users input the full file path of a given image, into an input field?
I am aware that this cannot be done using the method above for security reasons, however, I have seen this done before on various websites without any problems, I was wondering what I had to do to implement a similar file dialog that helps fill in the text, which is a full file path, of an input field?
It is not possible to get the file full path on local machine using browser and javascript.
However, as you would like to upload the file to the server, the easy possibility I see is to use html form with input type file. You will receive the file on your http server when the form is submitted.
Here is a very good url http://www.cs.tut.fi/~jkorpela/forms/file.html that explains the whole process nicely.