I'm trying to render vtk objects which are send from a webserver directly on the client using XTK without storing them to the disk. According to the XTK Documentation I just have to pass the vtk file as string into X.Mesh.filedata, but it just doesn't display anything when I'm trying to do that.
I want to do something like this:
var data = recieveVTKFileAsStringFromServer();
var r = new X.renderer3D();
r.init();
// create a mesh from a .vtk file
var dataset = new X.mesh();
// dataset.file = 'someFile.vtk';
dataset.filedata = data;
// add the object
r.add(dataset);
// .. and render it
r.render();
When I load the file from the file everything works just fine, setting it using filedata doesn't. Where is my mistake?
I also came up with the similar scenario to load the binary data directly using filedata instead of setting file attribute. I did this by passing dummy name in a file attribute along with actual binary data set in filedata and everything works fine.
var xhr = new XMLHttpRequest();
xhr.open('GET', '/test.nii', true);
xhr.responseType = 'arraybuffer';
xhr.send();
xhr.onreadystatechange = function (e) {
if (this.readyState === 4) {
var r = new X.renderer2D();
r.container = 'myImg';
r.orientation = 'Z';
r.init();
volume = new X.volume();
volume.file = "abc.nii";
volume.filedata = this.response;
r.add(volume);
r.render();
}
};
Related
I am following this and I want to upload any type of file to OneDrive. It says that it accepts a buffer for the file content but my following code does not seem to work in case of any type of file. The file gets uploaded but it cannot be opened so the contents are messed up for sure.
Using the following method I am trying to get the body contents so that I can send them with the request.
private fileToBuffer(file: File): Observable<any> {
return Observable.create(observer => {
var arrayBuffer;
var fileReader = new FileReader();
fileReader.onload = function () {
arrayBuffer = this.result;
observer.next(arrayBuffer);
observer.complete();
};
fileReader.readAsArrayBuffer(file);
});
}
I did not notice that the Angular 2's http's PUT was taking the body as string. So, I resorted to using XHR to upload a file with its contents.
var oReq = new XMLHttpRequest();
oReq.open("PUT", url, true);
oReq.setRequestHeader("Content-Type", "text/plain");
oReq.onload = function(e){
console.log('done');
};
oReq.send(arrayBuffer);
How to append blob to input of type file?
<!-- Input of type file -->
<input type="file" name="uploadedFile" id="uploadedFile" accept="image/*"><br>
// I am getting image from webcam and converting it to a blob
function takepicture() {
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(video, 0, 1, width, height);
var data = canvas.toDataURL('image/png');
var dataURL = canvas.toDataURL();
var blob = dataURItoBlob(dataURL);
photo.setAttribute('src', data);
}
function dataURItoBlob(dataURI) {
var binary = atob(dataURI.split(',')[1]);
var array = [];
for(var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
return new Blob([new Uint8Array(array)], {type: 'image/jpeg'});
}
// How can I append this var blob to "uploadedFile". I want to add this on form submit
It is possible to set value of <input type="file">.
To do this you create File object from blob and new DataTransfer object:
let file = new File([data], "img.jpg",{type:"image/jpeg", lastModified:new Date().getTime()});
let container = new DataTransfer();
Then you add file to container thus populating its 'files' property, which can be assigned to 'files' property of file input:
container.items.add(file);
fileInputElement.files = container.files;
Here is a fiddle with output, showing that file is correctly placed into input.
The file is also passed correctly to server on form submit. This works at least on Chrome 88.
If you need to pass multiple files to input you can just call container.items.add multiple times. So you can add files to input by keeping track of them separately and overwriting its 'files' property as long as this input contains only generated files (meaning not selected by user). This can be useful for image preprocessing, generating complex files from several simple ones (e.g. pdf from several images), etc.
API references:
File object
DataTransfer object
I had a similar problem with a fairly complex form in an angular app, so instead of the form I just sent the blob individually using XMLHttpRequest(). This particular "blob" was created in a WebAudioAPI context, creating an audio track in the user's browser.
var xhr = new XMLHttpRequest();
xhr.open('POST', 'someURLForTheUpload', true); //my url had the ID of the item that the blob corresponded to
xhr.responseType = 'Blob';
xhr.setRequestHeader("x-csrf-token",csrf); //if you are doing CSRF stuff
xhr.onload = function(e) { /*irrelevant code*/ };
xhr.send(blob);
You can't change the file input but you can use a hidden input to pass data. ex.:
var hidden_elem = document.getElementById("hidden");
hidden_elem.value = blob;
I had take too much time to find how to do "url, blob to input -> preview"
so I had do a example you can check here
https://stackoverflow.com/a/70485949/6443916
https://vulieumang.github.io/vuhocjs/file2input-input2file/
image bonus
I have a text file on my server and I want to upload a text in it using XMLHttpRequest. It is downloaded successfully via GET method, but when I try to POST it I get 404 error.
var r1 = new XMLHttpRequest();
r1.open("GET", "db.txt", false);
r1.send();
var str = r1.responseText + "foo text";
var r2 = new XMLHttpRequest();
r2.open("POST", "db.txt", false);
r2.send(str);
Doing a direct upload as you're trying would be a security concern in most places and is generally not permitted... What you need to do is have a middle layer on your server to handle the request and write the file to disk safely.
You can easily upload a file using something like this:
var jsonBlob = new Blob([someJSON], {type: "text/plain;charset=utf-8"});
var data = new FormData();
data.append("filename", "new.json");
data.append("json", jsonBlob);
var xhr = new XMLHttpRequest();
var postURL = "http://example.com/post_target";
xhr.open("POST", postURL, true);
xhr.onload = function(e) {
if (this.status == 200) {
console.log(e.target.response);
}
};
xhr.send(data);
Where postURL is an endpoint which can handle file uploads.
If you post what language(s) you have available on your server (PHP?) I can give some example code to handle the upload on the server's end.
I have a pdf with encoding UniJIS-UCS2-H. i want to convert it in to base 64 in javascript.
i wrote the code like this. It converting it in to pdf but the content is not visible.
my code is showing below.
function getBinary(file){
var xhr = new XMLHttpRequest();
xhr.open("GET", file, false);
xhr.overrideMimeType("application/pdf; charset=UniJIS-UCS2-H");
xhr.send(null);
return xhr.responseText;
}
function base64encode(binary) {
return btoa(unescape(encodeURIComponent(binary)));
}
var binary = getBinary('http://localhost/first.pdf');
var base64encoded = base64encode(binary);
data = "data:application/pdf;base64,"+base64encoded;
the data is contain only a plain pdf. how can i resolve it ?
Is it possible to view the raw data for an image file in javascript?
I'm trying to write a script that converts an image into its hex dump.
How can I view the data I'm writing to the image file?
You can do this with XHR:
var xhr = new XMLHttpRequest();
xhr.open('GET', '/my/image/file.png', true);
xhr.responseType = 'arraybuffer'; // this will accept the response as an ArrayBuffer
xhr.onload = function(buffer) {
var words = new Uint32Array(buffer),
hex = '';
for (var i = 0; i < words.length; i++) {
hex += words.get(i).toString(16); // this will convert it to a 4byte hex string
}
console.log(hex);
};
xhr.send();
Look at the doc for ArrayBuffers and TypedArrays
And you can see how I use it in testing here
Is it possible to get the source code of a file in javascript?
Find the URL for the script and load that into your browser. (Or use Firebug)