I'm trying to get a full URL using getData() after a drop event of an image:
function drop(e) {
e.stopPropagation();
e.preventDefault();
var url = e.dataTransfer.getData("url") || e.dataTransfer.getData("text/uri-list");
alert(url);
...
}
When I drop my image and capture the event my url = "http://localhost" and does not include the full url to the image. What is the correct way to capture the full url from a dropped image?
Thanks for your time.
As of this writing there is no way to get the full path of an uploaded file. The File API does not provide the full path name. This is what the specification says
The name of the file; on getting, this must return the name of the file as a string. There are numerous file name variations on different systems; this is merely the name of the file, without path information.
So there is no way you can get it as of now. This is done for security concerns.
Hope that helps :)
Related
If you right-click on any profile image on Github and open image in new tab you will see that it doesn't end with an extension
For example, here's the actual image of a user on github:
https://avatars0.githubusercontent.com/u/170270?s=60&v=4
Goal
I'm trying to add image saving functionality to my node.js app using request module:
// A proper image link (e.g. *.jpg)
let fileUrl_1 = "https://cdn.pixabay.com/photo/2016/06/20/03/15/pier-1467984_1280.jpg"
// Semi proper image link (e.g. *.jpeg?query)
let fileUrl_2 = "https://images.pexels.com/photos/371633/pexels-photo-371633.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260"
// Not a proper image link (e.g. filename[no extension]?query)
let fileUrl_3 = "https://avatars0.githubusercontent.com/u/170270?s=60&v=4"
let parsedPath = pathModule.parse(fileUrl_1)
let fileName = parsedPath.base
let destinationPath = `C:\\test\\${fileName}`
let request = require("request")
request
.get(fileUrl_1)
.on('error', function(err) {
console.log(err)
})
.pipe(fs.createWriteStream(destinationPath))
Problem
When I try to download images with normal paths like fileUrl_1 it works fine, but if I try to download images like fileUrl_2 or fileUrl_3 shown above I get an error:
ENOENT: no such file or directory, open 'C:\test\170270?s=60&v=4'
BUT, if you just right-click / save image as on a "problematic" image in any browser, you will get a save as dialog window and will be able to save this image as 170270.jpg
Question
How do you download any image with node.js like the save as dialog window does (retrive the image even if it doesn't end with a proper extension)?
It's entirely up to you to choose the destination filename, based on whatever you want. There is no problem in retrieving the image - your only problem is you are trying to save it with an invalid filename.
The server response may include a Content-Disposition header, which may include a recommended default filename.
The filename is always optional and must not be used blindly by the application: path information should be stripped, and conversion to the server file system rules should be done.
It should also include a Content-Type header from which you can derive a file extension, however this header may be incorrect.
Browsers will do MIME sniffing in some cases and will not necessarily follow the value of this header
Or you can "sniff" the first few bytes of the response body and check for a known magic number to indicate the file type.
pathModule.parse is designed to parse file paths, not URLs.
The examples you have where it fails to provide a valid filename are those with a ? in them.
Use a URL parser instead.
const url = require('url');
var fileName = url
.parse(
'https://images.pexels.com/photos/371633/pexels-photo-371633.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260'
)
.pathname.match(/\/([^\/]*)$/)[1];
console.log(fileName);
I have an object containing an array of slides. Every slide can have a media parameter containing the url to an image or video file or the link to a youtube or vimeo video.
My goal is to have the slides viewer zipped and inside the zip I also must have the image or video files taken from the urls.
To create the zip I'm currently using Archiver and it works fine, but I don't know how to put the media files inside the zip (possibly) without writing them on the filesystem first. I think I have to use streams, since archiver.append() can take a stream as first parameter, but I don't know how to do that.
I have implemented some code to understand if the url points to a file or not, writing the files' url inside an array (avoiding youtube or viemo urls).
This is how the zip is created:
...
var urls_array = ["http://url1/file1.jpg", "http://url2/file2.png"]; //the array of urls I take the media files from
var zip = archiver('zip');
zip.pipe(res);
zip.directory(__dirname + '/../../zip/', 'slideshow');
zip.append( new Buffer( file ), { name: 'slideshow/assets/slides.json' });
zip.finalize();
I suppose I have to cycle the url_array and for each url perform a http.get() call, but I can't understand how to .pipe() the response inside the zip.
Is there anyone who can help me?
Don't hesitate to ask me more information :)
Thank you in advance.
You should use the request method to create a stream from a remote URL to be passed to the append function of archiver, as a first argument, like this:
for ( var slide in slides ) {
archive.append( request( slide.url ), { name: slide.name } );
}
see archiver.append documentation ( https://archiverjs.com/docs/module-plugins_zip-Zip.html#append )
Hope it helps.
Here's the thing, I generate a PNG image in the application and I get an Image object with JavaScript, something like this...
var img = new Image();
img.src = 'data:image/png;base64,' + base64Img;
I want to save that image to the internal storage. Is there a plugin or a way I can do this?
According THIS QUESTION:
This is file download code which can be used by anyone. You just have three parameters to use this like-
1) URL
2) Folder name which you want to create in your Sdcard
3) File name (You can give any name to file)
All types of file can download by using this code. you can use this as .js
And this works on IOS also.
First step check parameters mismatch and checking network connection if available call download function
Second step to get Write permission and Folder Creation
Third step for download a file into created folder
Also check this link
function onPhotoDataSuccess1(imageData) {
alert(imageData);
sessionStorage.setItem("img_api",imageData);
$('#largeImage').attr('src','data:image/jpeg;base64,' + imageData);
}
Hope, it will helps you!
I am trying to read a local file and have each line as an index in an array using JavaScript. I have been searching for the past 20 minutes and either I'm stupid or there really isn't an answer that pertains to my problem (...but it's probably the former :P). I am really new to JavaScript so if you have an answer could you please comment the code just to I know what's going on?
Also, from the searching I've done on the internet some people said JavaScript can't read local file for security reasons so if that is correct is there another language I can use? I'm a bit familiar with PHP if that is an option, which I doubt it is.
EDIT
As per thg435's question, I'll explain what I am trying to accomplish.
My project is to analyze a BUNCH of water quality data that has been collected by the Ontario gov't (which I've done) and display it in some way. I have chosen to display it on a webpage using the Google Maps API. I currently have a file of chemicals that were found. Each line is a different chemical. I would like to read the file in an array then create an option menu displaying the chemicals in the array.
Also, the local file I would like to read will the be the same name and location all the time. I have seen people have boxes where the user clicks and chooses their file or to drag and drop but that's not what I'm looking for.
I don't think I explained this properly. I have a file in the same directory as my HTML and JavaScript files that contains words. Example:
Line 1: "Iron"
Line 2: "Aluminum"
Line 3: "Steel"
etc...
I would like to read the file and parse each line into a different index in an array. I don't want the user to be able to choose which file to read using the <input ... /> thing.
You're going to want to take a look at the FileReader API. This should allow you to read the text of a local file via readAsText(). This won't work in every browser but should work in all modern browser. You can see which browsers support it here.
Example:
<input id="file" type="file" />
var filesInput = document.getElementById("file");
filesInput.addEventListener("change", function (event) {
var files = event.target.files;
var file = files[0];
var reader = new FileReader();
reader.addEventListener("load", function (event) {
var textFile = event.target;
alert(textFile.result);
});
reader.readAsText(file);
});
It's not possible to invoke the FileReader API without user interaction. Consequently, your user would have to select whatever file to load in order for it to be read in pure JS. Since I'm assuming this will be up on a server, why not just put the list of chemicals also up on the server and GET the JSON encoded array of the results. Then you can decode them with Javascript.
You can access local files in 2 ways that I know of. The first way is making the user drag-and-drop the files onto the page, and using an <input type="file"> tag.
For the former, you would need to do the following:
addEventListener('dragover', function(e){e.preventDefault();});
addEventListener('drop', function(e) {
eventHandler.call(e.dataTransfer||e.clipboardData);
e.preventDefault();
});
For the latter, you'd need to add an event listener for the change event on the input:
document.getElementById('upload').addEventListener('change', eventHandler)
And for both, you'd need to have this as a basic callback function:
function eventHandler() {
var file = this.files[0]; //get the files
var reader = new FileReader(); //initiate reader
reader.onloadend = callbackFn; //set event handler
reader.readAsText(file); //initiate reading of files
if (this.id) { //only run if this is the input
var id = this.id;
this.outerHTML = this.outerHTML; //this resets the input
document.getElementById(id).addEventListener('change', eventHandler); //reattach event handler
}
function callbackFn(e) {
document.getElementById('output').value = e.target.result; //output it to a textarea
}
}
Here is a demo where the text contents (that what you see when opening it in notepad) of any file you drop in it, or any file you select from the input, is put in the textarea.
For more information, see https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications.
When one right clicks an image in a webpage and selects "Properties", one gets a display which details the URL, Size, Dimensions, Created (date), Modified (date), etc.
Obviously I know the URL as it is in my code, but some of the others are not, for example created and modified dates, they have to be coming from the server at the image source. I have tried using the
document.getElementById("photo").attributes
where the related HTML code is this
<img id="photo" src="http://www.somesite.com/photo.jpg" width="320" height="240" alt="offline" >
but that only returns the 5 attributes found in the above img line.
Since the dates and other information are available for the "Properties Dialogue" I assume there are also available somewhere in the document object.
Any ideas as to how I might access them using JavaScript or VBScript?
Thanks....RDK
Have you investigated using the JavaScript Image object?
Well, you could try get the the URL of the image, then do an AJAX request to the image, get the response headers and they will tell you the created date, etc.. that you are after...
Example...
var myImageURL = %YOUR_IMAGE_URL%
var modifiedHeader = 'Last-Modified';
var req = new XMLHttpRequest();
req.open('HEAD', myImageURL, false);
req.send();
var header = req.getResponseHeader(modifiedHeader);
if (header) {
console.log(header); // this is the last modified date
}
EDIT:
This would work only if the image was accessible via AJAX... (same-origin policy, etc...)
EDIT:
Changed to head so SOP does not matter now.. Thanks #Musa
Information like the creation and modification dates will be stored (if anywhere) in the image's EXIF metadata.
There is a jQuery library for reading EXIF metadata that provides an exif() method, e.g. $('img').exif('DateTimeOriginal').
Note that images hosted on a different domain will not be accessible to JavaScript.
Information about the width and height of the original image file should be properties of the image object itself, e.g. document.getElementById('photo').naturalHeight