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();
Related
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.
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.
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
I'm using a 3rd party library which wants to load in a file via the HTML file system, as in:
<input id="fileupload" type="file" onchange="LoadAndDisplayFile(this.files[0])">
This works great, except I'd like to pass in a url to a file stored on the serverr rather than have the user upload a file.
I tried using:
var myFile = new File ("path/to/file");
with the hope that I'd then be able to pass myFile into LoadAndDisplayFile()
but I get the following error:
Uncaught TypeError: Failed to construct 'File': 2 arguments required, but only 1 present.
I'm sure this is a noob question, but what am I missing here?
You cannot create a File object only giving an URL to it.
The right method is to get the file through a Http request and read it, with something like this:
var blob = null
var xhr = new XMLHttpRequest()
xhr.open("GET", "path/to/file")
xhr.responseType = "blob"
xhr.onload = function()
{
blob = xhr.response
LoadAndDisplayFile(blob)
}
xhr.send()
I was dealing with same error and after spending time I created new File object using below code
new File(
[""],this.name,{
lastModified: 1605685839310,
lastModifiedDate: new Date(),
size: this.size,
type: "",
webkitRelativePath: ""
});
I have an audio stream from an external server and am not able perform any serverside changes. It currently works pretty well but it's only able to stream the songs in an HTML5 audio element. I'd also like to implement a download feature, the problem is, a link doesn't download anything, it automatically streams the mp3. The HTML5 download attribute doesn't do anything.
The complete Response Headers by the server:
Accept-Ranges:bytes
Cache-Control:no-cache, no-store, must-revalidate
Connection:close
Content-Length:6991749
Content-Type:audio/mpeg
Date:Sun, 28 Apr 2013 19:40:49 GMT
Expires:Sat, 26 Jul 1997 05:00:00 GMT
Last-Modified:Thu, 10 Jan 2013 18:59:31 GMT
Server:nginx/1.0.2
It should work completely in JavaScript, if possible without PHP proxy.
It turns out my initial pessimism (about this being impossible) might have misguided. Here is a demo that makes use of some of the HTML5 File API (not as advanced as some of the stuff I've been reading about, but it seems security limitations make totally automating this a bit out of reach at the moment, this demo works in Firefox and Chrome but I would guess only IE10 could stand a chance at supporting it.
var createObjectURL = function (file) {
if (window.webkitURL) {
return window.webkitURL.createObjectURL(file);
} else if (window.URL && window.URL.createObjectURL) {
return window.URL.createObjectURL(file);
} else {
return null;
}
},
xhr = new XMLHttpRequest();
xhr.open('GET', 'http://upload.wikimedia.org/wikipedia/commons/6/63/Wikipedia-logo.png', true);
xhr.responseType = 'blob';
xhr.onload = function (e) {
if (this.status == 200) {
var url = createObjectURL(new Blob([this.response], {
type: 'image/png'
}));
var link = document.createElement('A');
link.setAttribute('href', url);
link.setAttribute('Download', 'Name I Want it to have.png');
link.appendChild(document.createTextNode('Download'));
document.getElementsByTagName('body')[0].appendChild(link);
}
};
xhr.send();
Here I am using XMLHttpRequest to request a PNG, then I'm storing it in a Blob and creating a download URL with some extra information that triggers the browser to download the asset instead of just linking to it (which is what it would do with a PNG). I couldn't find a Grooveshark URL that didn't require some session key, so I don't know if this will work for you, but that limitation comes from Groovshark's efforts to prevent hot linking to songs.
I did it now,
the problem was, that the server automatically refused access to the temporary created Stream URI when it was requested once. I just commented out the HTML5 audio element and only placed an download link with the new HTML5 Download attribute
<a href="stream.com/stream.mp3" download="filename.mp3">
If i would not have set the "download" attribute, the browser would have automatically streamed the file.
Thumbs up to HTML5!