How to to get Image file metadata from it's path - javascript

I want to upload a image file from Reactjs which is in my project folder ("../assets.cover.png") without using input, when I'm trying import cover from "../assets.cover.png" it's giving me file path but what I need is file metadata to upload it.
Basically my final intention is to upload that image file and calculate user upload speed.

I was able to resolve it after reading after reading this documentation
import cover from "../assets/cover.png"; // importing img file
let blob = await fetch(cover).then((r) => r.blob()); //creating blob object
const file = new File([blob], "cover.png", {
type: "image/png",
});
console.log(file);
// output
// {
// lastModified: 1656486792733
// lastModifiedDate: Wed Jun 29 2022 12:43:12 GMT+0530 (India Standard Time) {}
// name: "cover.png"
// size: 1446458
// type: "image/png"
// webkitRelativePath: ""
// }

The imported image is just a file path relative to the base url for use on properties, you'll have to read the file to do what you are attempting.

Related

Uploaded file's filepath node

I uploaded a file in node using the
Input type:"file"
The object generated by the Input field is as follows
{
lastModified: 1524895591000
lastModifiedDate: Date 2018-04-28T06:06:31.000Z
name: "images.jpeg"
size: 10732
type: "image/jpeg"
webkitRelativePath: ""
}
How do I get the full path to the file in node? I am on a ubuntu 17.10
Update:
I basically need the full path for the file FileToBeUploaded.txt, Which will be something like
/home/m/Desktop/FileToBeUploaded.txt
So I can execute a child process command on the file Path of the uploaded file.

Javascript loading mp3 file as blob

I have a javascript function that for various reasons I cant change any of the code inside, the parameter for e that is passed to the function is a file selector mp3 file that the user "uploads"
this is the structure of the function-
let handleFileSelection = function(e) {
fileStore = e.target.files[0];
//go off and do other stuff with fileStore
}
this is the structure of fileStore when the file selector passes an mp3 to the function-
lastModified:1508423505000
lastModifiedDate:Thu Oct 19 2017 15:31:45 GMT+0100 (GMT Daylight Time) {}
name:"audioFile.mp3"
size:5571549
type:"audio/mp3"
webkitRelativePath:""
is it possible to pass a locally stored mp3 file to the function instead in such a way that the fileStore will have the same information ?
To clarify: The function currently accepts an mp3 file from a file selector, I need it to accept a locally stored mp3 file and for the fileStore to have the exact same information as if i was passing a file from the file selector, is this possible without modifying the function ?

converting <svg> element to a file object in JavaScript [duplicate]

There's a File object in JavaScript. I want to instantiate one for testing purposes.
I have tried new File(), but I get an "Illegal constructor" error.
Is it possible to create a File object ?
File Object reference : https://developer.mozilla.org/en/DOM/File
According to the W3C File API specification, the File constructor requires 2 (or 3) parameters.
So to create a empty file do:
var f = new File([""], "filename");
The first argument is the data provided as an array of lines of text;
The second argument is the filename ;
The third argument looks like:
var f = new File([""], "filename.txt", {type: "text/plain", lastModified: date})
It works in FireFox, Chrome and Opera, but not in Safari or IE/Edge.
Now you can!
var parts = [
new Blob(['you construct a file...'], {type: 'text/plain'}),
' Same way as you do with blob',
new Uint16Array([33])
];
// Construct a file
var file = new File(parts, 'sample.txt', {
lastModified: new Date(0), // optional - default = now
type: "overide/mimetype" // optional - default = ''
});
var fr = new FileReader();
fr.onload = function(evt){
document.body.innerHTML = evt.target.result + "<br>Download " + file.name + "<br>type: "+file.type+"<br>last modified: "+ file.lastModifiedDate
}
fr.readAsText(file);
Update
BlobBuilder has been obsoleted see how you go using it, if you're using it for testing purposes.
Otherwise apply the below with migration strategies of going to Blob, such as the answers to this question.
Use a Blob instead
As an alternative there is a Blob that you can use in place of File as it is what File interface derives from as per W3C spec:
interface File : Blob {
readonly attribute DOMString name;
readonly attribute Date lastModifiedDate;
};
The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system.
Create the Blob
Using the BlobBuilder like this on an existing JavaScript method that takes a File to upload via XMLHttpRequest and supplying a Blob to it works fine like this:
var BlobBuilder = window.MozBlobBuilder || window.WebKitBlobBuilder;
var bb = new BlobBuilder();
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://jsfiddle.net/img/logo.png', true);
xhr.responseType = 'arraybuffer';
bb.append(this.response); // Note: not xhr.responseText
//at this point you have the equivalent of: new File()
var blob = bb.getBlob('image/png');
/* more setup code */
xhr.send(blob);
Extended example
The rest of the sample is up on jsFiddle in a more complete fashion but will not successfully upload as I can't expose the upload logic in a long term fashion.
Now it's possible and supported by all major browsers: https://developer.mozilla.org/en-US/docs/Web/API/File/File
var file = new File(["foo"], "foo.txt", {
type: "text/plain",
});
The idea ...To create a File object (api) in javaScript for images already present in the DOM :
<img src="../img/Products/fijRKjhudDjiokDhg1524164151.jpg">
var file = new File(['fijRKjhudDjiokDhg1524164151'],
'../img/Products/fijRKjhudDjiokDhg1524164151.jpg',
{type:'image/jpg'});
// created object file
console.log(file);
Don't do that ! ... (but I did it anyway)
-> the console give a result similar as an Object File :
File(0) {name: "fijRKjokDhgfsKtG1527053050.jpg", lastModified: 1527053530715, lastModifiedDate: Wed May 23 2018 07:32:10 GMT+0200 (Paris, Madrid (heure d’été)), webkitRelativePath: "", size: 0, …}
lastModified:1527053530715
lastModifiedDate:Wed May 23 2018 07:32:10 GMT+0200 (Paris, Madrid (heure d’été)) {}
name:"fijRKjokDhgfsKtG1527053050.jpg"
size:0
type:"image/jpg"
webkitRelativePath:""__proto__:File
But the size of the object is wrong ...
Why i need to do that ?
For example to retransmit
an image form already uploaded, during a product update, along with additional images added during the update
Because this is javascript and dynamic you could define your own class that matches the File interface and use that instead.
I had to do just that with dropzone.js because I wanted to simulate a file upload and it works on File objects.

Loading a video file without input upload

I am incidently using react but the fact remains: when I put up a simple page with an input to upload a local file, if I console.log the actual file once it has been selected, here is what I get from the console:
File {name: "myfile.mp4", lastModified: 1474084788000, lastModifiedDate: Fri Sep 16 2016 23:59:48 GMT-0400 (EDT), webkitRelativePath: "", size: 27828905…}
lastModified: 1474084788000
lastModifiedDate: Fri Sep 16 2016 23:59:48 GMT-0400 (EDT)
name: "myfile.mp4"
size: 27828905
type: "video/mp4"
webkitRelativePath: ""
__proto__: File
And so the file loads in the video tags and I can watch it. (The code is below...)
Then, if I want to load the same file but from a hardcoded full path instead, like so: "file:///path/to/myfile.mp4", an error pops up This video file format is not supported. and what I get back from the console is the exact same path that I had previously hardcoded.
My question is how should one load a local file by using a hardcoded path instead of selecting a file from an input element?
OR
How to create an objectURL directly from a local path?
I've already tried to Blob the file before passing it on to the URL.createObjectURL function but, unless I did it something wrong, it didn't work out.
Render function code:
render() {
return (
<div>
<input type="file" ref="input" onChange={this.upload} />
<video ref="video" type="video/mp4" controls loop autoPlay width="720"></video>
<div ref="message"></div>
</div>
);
}
Functions:
processs = (file) => {
let fileURL = URL.createObjectURL(file);
this.refs.video.src = fileURL;
}
playFile = (event) => {
let file = event.target.files[0];
console.log(file);
//check if video can be played
if(this.refs.video.canPlayType(file.type) != ""){
this.processs(file);
} else {
this.refs.message.innerHTML = "This video file format is not supported."
}
};
Here is a working demo
Load Image or Video without Upload
Hope it helps
How to create an objectURL directly from a local path?
You can use XMLHttpRequest with responseType set to "blob". File inherits from Blob, you can pass returned Blob to your existing function which expects File object. See also Loading images from file with Javascript
var request = new XMLHttpRequest();
request.responseType = "blob";
request.open("GET", "file:///path/to/myfile.mp4");
request.onload = () => {
// do stuff with `request.response` : `Blob`
}
request.send();

File object to image with correct file name instead of src="blob..."

I have a File object myFile that looks like this in console:
File {
name: "myimage.jpg",
lastModified: 1465476925001,
lastModifiedDate: Thu Jun 09 2016 14:55:25 GMT+0200 (CEST),
size: 33002
type: "image/jpeg"
}
But when i create an image out of it with
var image = new Image();
image.src = URL.createObjectURL(myFile);
I get:
<img src="blob:http://myurl.com/6b2b83d8-ac36-40c1-8ab1-c4f07b019ba5">
When i try to save the file with right-click, the file-name is empty or "6b2b83d8-ac36-40c1-8ab1-c4f07b019ba5" instead of "myimage.jpg". The file-name from the file-object is gone. Is there any way to set the image file name?
The Problem
The File object is sort of an extended version of a Blob that allows it to hold metadata such as filename, size etc.
However, while createObjectURL() will reference both File and Blob the data read through the blob: protocol will only consist of the binary file data itself as when loading via other protocols. No metadata (such as filename) will be provided via the protocol.
Other examples where filename is not considered could be when an image is loaded via for example a PHP or ASPX page (/getimage.aspx?id=1). Also here there is no metadata provided and browser would suggest something like "getimage.aspx%3Fid=1" as filename in this case. As expected.
The IMG tag itself never assumes any filename even if one is used at source point; it only holds what is given to it via the src attribute/property as-is, as a connection point to retrieve the needed binary data for decoding.
In this case the source point is blob:*/* which then will be what IMG tag references via src, and is what the browser use when the data is to be saved.
Workarounds
The only way to hold on to a filename from the File object is to keep track of it so you have access to it when needed for download.
But also this is limited as you can only specify a filename using the download attribute in an A tag. And of course, some browsers such as <= IE11 does not support this attribute.
<img ..>
In IE10+ there is the proprietary method msSaveBlob() which can be used instead though:
window.navigator.msSaveBlob(myBlob, 'filename.jpg');
Besides from these there are no common way to specify a default filename from within the client.
Example fiddle

Categories

Resources