How to read hardcoded image file using javascript / jquery - javascript

Is it possible to use hardcoded filename?
I want to read File of an image.
I have hardcoded filename like, '/Users/Desktop/1.jpg' and i want to use this
as a file.
I want to change this '/Users/Desktop/1.jpg' type as file.
var imageURL = '/Users/Desktop/1.jpg';
new File(imageURL);
alert(typeof(imageURL)); // I want this as a File

The simplest approach would be to click or drag and drop the file at an <input type="file"> element.
<input type="file" accept="image/*">
<script>
const input = document.querySelector("input");
input.onchange = function(event) {
const file = event.target.files[0];
console.log(file);
}
</script>
If the file is served with CORS headers you can request the file using Image constructor and pass the <img> reference to canvas.toBlob(), then pass Blob reference to File constructor, optionally set the name of the File object.
Similarly CORS headers are necessary when using fetch() and Response.blob() to get Blob of image.
Note if using Chrome or Chromium browser to request files at local filesystem you can launch Chrome or Chromium browsers with --allow-file-access-from-files flag to access local filesystem at JavaScript and HTML, see Read local XML with JS.

Related

How to load 3-D models specifying file content rather than path in three.js?

I want to create an online viewer where a user can upload models and view them, rather than having to edit the path in the source code.
Since browsers don't allow to retrieve file path but I can read the contents of the file, how do I load a model (obj, ply, mtl etc) given the contents of the file?
There a couple ways to do it, but if you go to the github three.js repository, in the examples you'll see an obj loader. There are examples with mtl, stl, collada, etc.
http://threejs.org/examples/webgl_loader_obj.html
The repository has the examples folder which has a js folder with all the example loaders:
https://github.com/mrdoob/three.js/tree/master/examples/js/loaders
If you want to subvert the internal three loader, each loader example has a parse(text) method.
Well just found out that the three.js online editor does this #http://threejs.org/editor/ .
File -> Import.
You can use the HTML5 filereader API and then you can call parse method from the corresponding loader directly with the result.
Or you can use the file reader, read the file into a data url and load the data url instead of your normal url.
HTML code allowing user to load the model file
<h1>Model File Reader</h1>
<div>
Select a model file:
<input type="file" id="fileInput">
</div>
Javascript code to handle the onload event:
window.onload = function() {
var fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', function(e) {
// file selection is done you can now read the file
var file = this.files[0];
// set your file encoding
var encoding = 'ISO-8859-1';
// create a file reader
var reader = new FileReader();
// set on load handler for reader
reader.onload = function(e) {
var result = reader.result;
// parse using your corresponding loader
loader.parse( result );
}
// read the file as text using the reader
reader.readAsText(file, encoding);
});
}
Check here for more information on the file reader class

get file object using full path

is there a way to get a file object using the directory full path of the file itself? this piece of code wont work:
var file1 = new File("D:\\path\\to\\file\\file.txt");
I need to get the file object since I have a function that has a file object as its parameter.
bryan
That would be very tragic if browsers could suddenly start accessing users' file systems without their permission.
I would suggest using <input type="file">. This way the user chooses which file they will allow the browser to access.
I would suggest you to use: <input type="file" id="fileUpload"> and get the file name using
$('input[type=file]').change(function () {
console.log(this.files[0])
});

select a file without browsing using javascript

My main program prompts the user to browse for a file in order to convert it using ffmpeg. This is the format of the file browsing:
<div>
<p class="lead">1. Select audio file for conversion ( mp3, wma):</p>
<div class="quick-center">
<div class="quick-drop-outer quick-left"><input id="inFile" type="file" id="inputFile"/></div>
</div>
</div>
and this is the code where to launch the file and convert it according to selection: not whole code supported because no need of file conversion:
document.getElementById('inFile').addEventListener('change', handleFileSelect, false);
function readInputFile(file) {
// disable conversion for the time of file loading
$('#convert').attr('disabled', 'true');
// load file content
var reader = new FileReader();
reader.onload = function(e) {
$('#convert').removeAttr('disabled');
fileName = file.name;
fileBuffer = e.target.result;
}
reader.readAsArrayBuffer(file);
}
function handleFileSelect(event) {
var files = event.target.files; // FileList object
// files is a FileList of File objects. display first file name
file = files[0];
console.log(file);
if (file) {
$("#drop").text("Drop file here");
readInputFile(file);
}
}
now, here is my problem, what I want to do is to upload the file directly from a selected folder (upload) where the audio files are already there. I want instead of browsing for the file, I want the last file in the upload folder to be uploaded instead of "inFile" so that conversion can happen.
how could that happen.
edit: A small brief about my project. the user records his voice using HTML5 and the link of that audio is uploaded using ajax and php into a folder named upload.what I simply want is instead of browsing that file, I want to write down the path of the file in the selected folder automatically once recording is done for conversion.so, instead of dropping the file by user, the file would be dropped and conversion starts from there.
help please.Thank you in advance
From JavaScript You dont have access to files and directories on host system.
Why?
Because is VERY IMPORTANT SECURITY feature to block reading Your disc for files from scripts.

file path from input tags in javascript

Can I pick the file path from an input tag in javascript? For example:
<input id="file" type="file" onchange="getpath()" />
This can be done in some older browsers, but in correct implementations, the Javascript security model will prevent you from reading the path.
You can’t get at the full path to the file (which would reveal information about the structure of files on the visitor’s computer). Browsers instead generate a fake path that is exposed as the input’s value property. It looks like this (for a file named "file.ext"):
C:\fakepath\file.ext
You could get just the filename by splitting up the fake path like this:
input.onchange = function(){
var pathComponents = this.value.split('\\'),
fileName = pathComponents[pathComponents.length - 1];
alert(fileName);
};

HTML5: drag out a JS generated file

I have a feeling security concerns may not allow this but is it possible to generate a file with JavaScript and allow the user to drag it to the desktop (or file system)?
The following code drags out a file from a server
files[0].addEventListener("dragstart",function(evt){
evt.dataTransfer.setData("DownloadURL", "application/octet-stream:Eadui2.ttf:http://thecssninja.come/demo/gmail_dragout/Eadui.ttf");
},false);
And with the below code I can generate a file and have it download but I can't set the file name or let the user select the location.
var uriContent = "data:application/octet-stream," + encodeURIComponent(JSON.stringify(map));
location.href = uriContent;
Ideally I'd like a magical combination of both.
following code is currently working in Chrome only:
// generate downloadable URL, file name here will not affect stored file
var url = URL.createObjectURL(new File([JSON.stringify(map)], 'file_name.txt'));
// note that any draggable element may be used instead of files[0]
// since JSON.stringify returns a string, we use 'text' type in setData
files[0].addEventListener("dragstart", function(evt) {
evt.dataTransfer.setData("DownloadURL", "text:file_name.txt:" + url);
}, false);
now, dragging our files[0] element from the browser to desktop or file system, will store there a text file called, file_name.txt.
Feel free to choose another file name :)
This is only possible for Chrome, and even in Chrome you can't set the location. If using only Chrome is okay then you will have the following options:
Stick with Drag n' Drop like from the CSS Ninja's tutorial, then you should try Ben's answer. encodeURIComponent is one way, but if you have the file generated using BlobBuilder then you can use window.webkitURL.createObjectURL() to get the file's URL. You can also try using FileWriter() with requestFileSystem(TEMPORARY, ...).
Chrome supports download attribute for anchor tags so you can have regular link for the user to click (dragging also works):
Download
For cross browser support I suggest Downloadify.
You could try sending it to the server, saving the file, checking the return value and firing the download file function, followed by a server file that deletes the file from the server.
Something like this (with jQuery)
$.ajax({
url: 'saveFile.php',
method: 'post',
data: {
Filedata: data// file data variable
},
success: function(d) {
// save file function, where d is the filename
}
})
PHP:
$filename = ;//generate filename
file_put_contents($filename, $_POST['Filedata']);
echo $filename;
Obviously there is more to it but that should be the basics

Categories