I have the following javascript code which is trying to upload a file to a repository but I need to pass it as a buffer first. The problem is my "getBatchFileBuffer" function is somehow continuing without waiting for it to resolve which make the "UploadFiles" to only get a promise and not the real object. TIA
const getBatchFileBuffer = file => {
return new Promise((resolve, reject) => {
var reader = new FileReader();
reader.onloadend = function(e) {
file[0].fileBuffer = e.target.result;
resolve(file);
};
reader.readAsArrayBuffer(file[0].fileObject);
});
};
getBatchFileBuffer(self.state.tempAttachment).then(function(
tempAttachment
) {
self.setState({ tempAttachment });
UploadFiles(
self.state.AppMainObject.ID,
getBatchFileBuffer(self.state.tempAttachment)
).then(function(UploadFilesFileURL) {
console.log(UploadFilesFileURL);
});
});
I think I know the solution, I was calling the "getBatchFileBuffer" twice. That was my mistake
Related
How I can get media.duration to live in a state environment ?
Right now I don't have access to it, even after trying to change state
handleClick(e) {
e.preventDefault();
var reader = new FileReader();
reader.readAsDataURL(this.state.uploadedFile);
reader.onload = function() {
var media = new Audio(reader.result);
media.onloadedmetadata = function() {
console.log(media.duration); // <-- THIS WORKS!!!!!!!!!!!!!!
};
};
console.log(media.duration) //<------THIS DOES NOT WORK!!!!!!!!!!
console.log("The link was clicked.");
console.log(this.state.duration);
}
from: How to get duration of video when I am using filereader to read the video file?
_________________________________________
I tried this but it did not work
this.setState({duration:media.duration},()=>{
console.log(this.state.duration)
})
It's because you use media variable is out of the scope.
Please try this one.
handleClick(e) {
e.preventDefault();
var reader = new FileReader();
reader.readAsDataURL(this.state.uploadedFile);
reader.onload = () => {
var media = new Audio(reader.result);
media.onloadedmetadata = () => {
console.log(media.duration); // <-- THIS WORKS!!!!!!!!!!!!!!
this.setState({duration: media.duration});
};
};
}
I want to set state, but this.state is not working, can anyone please check this code, and help me what's issue in that, here is my code
save_import_permit() {
//alert('sdsdsd');
var file_name = jQuery('input[type=file]').val().split('\\').pop(); //jQuery('#permit_csv_file').prop('files')[0];
let files = jQuery('input[type=file]')[0].files[0];
console.log(files);
let reader = new FileReader();
let data = [];
reader.readAsDataURL(files);
reader.onload = function(e) {
console.log(e.target.result);
data.result = e.target.result;
data.action = 'Permity::saveImportCsvFile';
const url = 'admin-ajax.php';
const formdata = "file="+data.result+"&action="+data.action;
this.state({loading:'loading_show'})
return post(url,formdata,function (r) {
this.state({loading:'loading_hide'});
alert(r.data.msg)
}.bind(this));
}.bind(this);
}
You shouldn't attribute a value to the state using this.state, you should always use this.setState(), wichs is a build-in function of the react framework. Check this link to know better.
So you need to change
this.state({loading:'loading_show'})
to
this.setState({loading:'loading_show'})
getImage(file) {
let context = this;
let reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
context.setState({
images: e.target.result,
});
};
})(file);
reader.readAsDataURL(file);
}
Error: TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.
Files that comes from a <input /> of type file are stored in an array form.
If GetImage is the callback of the onChange event of your <input /> you need to extract it in the following form:
function getImage(event) {
const file = event.target.files[0];
// ...code
reader.readAsDataURL(file);
}
I'm trying to encrypt a video using the CryptoJS library. The goal is to encrypt it and store it in Firebase Storage. Later, when you want to visualize, it is decrypted and added as an url to the HTML video tag. I can't get the video displayed after decrypting it, any idea of what the problem is? I have the feeling that the problem is with treating the output of the cipher as a string. I don't know in what way I should treat it so that it continues to maintain the properties of a video file. Thanks in advance.
The current code is:
//Encrypt and upload function
function almacenarFicheroGrabacionVideo(file) {
let storageRef = firebase.storage().ref('videos/' + file.name);
let reader = new FileReader();
reader.onload = function () {
let read = reader.result;
let task = storageRef.putString(CryptoJS.AES.encrypt(read, getCookie('key')).toString());
task.on('state_changed', function progress(snapshot) {
}, function error(err) {
console.log(err);
}, function complete() {
console.log("fichero subido");
});
};
reader.readAsText(file);
}
//Decrypt and visualize video
$scope.verVideo = function() {
firebase.storage().ref('videos/').child('Blurred Bokeh Video 2.mp4').getDownloadURL().then(function (url) {
fetch(url)
.then(res => res.blob()) // Gets the response and returns it as a blob
.then(blob => {
let reader = new FileReader();
reader.onload = function () {
let fileDown = CryptoJS.AES.decrypt(reader.result, getCookie('clave')).toString(CryptoJS.enc.Utf8);
var videoNode = document.getElementsByTagName('video')[0];
let blob = new Blob([fileDown], {type: "video/mp4"});
let url = URL.createObjectURL(blob);
let element = document.createElement('a');
element.setAttribute('href', url);
element.setAttribute('download', 'Blurred Bokeh Video 2.mp4');
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
};
reader.readAsText(blob);
});
}).catch(function (error) {
// Handle any errors
console.log(error);
});
};
I have a FileInput in my render function
<FileInput
accept= "image/jpeg,image/png,audio/mp3"
onChange= {this.fileInputOnChange}
children= {<i className="fa fa-paperclip"/>}
className= 'fileInput'
/>
I need to write a test for file upload, when I simulate the change function it call the function fileInputOnChange
fileInputOnChange: function(evt){
var file = evt.target.files[0];
var fileReader = new FileReader();
fileReader.onload = function(readFile){
// Check the file type.
var fileType = file.type.toLowerCase();
if(fileType.lastIndexOf('image') === 0 && (fileType.lastIndexOf('png') >= 0 || fileType.lastIndexOf('jpeg'))){
var image = new Image();
image.onload = function(){
var attachedFile = {
attached: file,
mediaSource: readFile.target.result,
type: 'image'
}
this.props.onChange(attachedFile);
}.bind(this);
image.onerror = function(){
this.props.onError("INVALID_TYPE");
}.bind(this);
image.src = readFile.target.result;
}else if(fileType.lastIndexOf('audio') === 0 && fileType.lastIndexOf('mp3') >= 0){
//#todo: manage audio upload here
var audio = new Audio();
audio.oncanplaythrough = function(){
var attachedFile = {
attached: file,
mediaSource: readFile.target.result,
type: 'audio'
}
this.props.onChange(attachedFile);
}.bind(this);
audio.onerror = function(e){
this.props.onError("INVALID_TYPE");
}.bind(this)
audio.src = readFile.target.result;
}else if (fileType.lastIndexOf('video') === 0 && fileType.lastIndexOf('mp4') >= 0){
var video = document.createElement('video');
video.oncanplaythrough = function(){
var attachedFile = {
attached: file,
mediaSource: readFile.target.result,
type: 'video'
}
this.props.onChange(attachedFile);
}.bind(this);
video.onerror = function(){
this.props.onError("INVALID_TYPE");
}.bind(this)
video.src = readFile.target.result;
}
}.bind(this);
fileReader.onerror = function(){
this.props.onError("READING_ERROR");
}.bind(this)
fileReader.readAsDataURL(file); }
I could not add any files while simulating the upload button, I am confused of how to write the test for this scenario. Anyone ever came across this kinda scenarios? I would be greatful for all sorta helps.
it('testing attachfile change function...',()=>{
const wrapper=shallow(<AttachFile />);
wrapper.find('FileInput').simulate('change');
console.log(wrapper.debug());
});
When I tried the above test I got the following error
TypeError: Cannot read property 'target' of undefined
at [object Object].fileInputOnChange (js/components/home/chats/AttachFile.react.js:11:16)
at node_modules/enzyme/build/ShallowWrapper.js:768:23
at ReactDefaultBatchingStrategyTransaction.Mixin.perform (node_modules/react/lib/Transaction.js:138:20)
at Object.ReactDefaultBatchingStrategy.batchedUpdates (node_modules/react/lib/ReactDefaultBatchingStrategy.js:63:19)
at batchedUpdates (node_modules/react/lib/ReactUpdates.js:98:20)
at node_modules/enzyme/build/ShallowWrapper.js:767:45
at withSetStateAllowed (node_modules/enzyme/build/Utils.js:196:3)
at ShallowWrapper.simulate (node_modules/enzyme/build/ShallowWrapper.js:764:42)
at Context.<anonymous> (test/sample.js:40:27)
You'll need to provide a mocked event object, something like:
wrapper.find('FileInput').simulate('change', {
target: {
files: [
'dummyValue.something'
]
}
});
Your component its making a lot of work inside, its like a huge side effect (it defines two callbacks with logic nailed). It's going to be difficult, but I suppose you'll need to mock FileReader as well using two spies, one reacting to the readAsDataURL calling the onload and another one calling the onerror.
Then you can check if your callbacks are doing what is supposed to.
Hope it helps!