How to get file size from file path with js? - javascript

I want to get the size of a file from this path:
my-path/filename
How can I get the size of this file?

Use the fetch() method and only set the request method to HEAD.
const fetchResponse = await fetch(src, { method: 'HEAD' });
const size = fetchResponse.headers.get('content-length');
Beware, it will return a number represented as a string.

Related

I am turning base64 string to its previous value(image) using blob and file but when sending to the server it says `unprocessable content`

I have following problem. I am saving image to local storage by converting it to string base 64 format via file reader.readAsDataUrl. it is stored properly. Now I want to send that image to the server. I am using fetch to fetch url and then blobing it to form a file. when i console.log i get same file as I got before converting to base 64 exept name is different. but when sending to the server that file object it returns unprocecable content. The image must be an image.
fr.readAsDataURL(value);
fr.addEventListener("load",() => {
// assigning freader value to state and refferencing it to `newVal`
// saving only happens inside `this` eventListener
try{
const newVal = generalInfo[iName][0] = fr.result;
// console.log(newVal)
setGeneralInfo({...generalInfo,newVal});
localStorage.setItem("generalP", JSON.stringify(generalInfo));
}
catch(e){
alert("photo sized more than 1mb cannot be uploaded");
// get back to current state values using LC
getFromLC();
}
})
and here is retrieving from local storage and turning it into file
const getSendingData = async () => {
//strip off the data uri prefix
// getting base64 string as data url
const response = await fetch(generalInfo.photo[0]);
const blob = await response.blob();
const file = new File([blob],'image',{type: blob.type});
// continue from here
console.log(file)
}

Excel file from server to client | Javascript

What I want to do: I have on the server side a file 'test_download.xlsx', and want to send it to the client side so that I can apply XLSX.read() on the retrieved object.
So I tried it this way
Server :
let filename = 'test_download.xlsx';
const buffer = fs.readFileSync(filename)
res.json(buffer);
Client :
file = await axios.get('/dataexplorer/test');
console.log(file);
console.log(XLSX.read(file.data, {type: "buffer"}));
First log :
Second log :
The problem is that it doesn't match my excel file at all just in terms of sheets (my file has 3 different sheet names)
Do you have any idea what the problem is?
Thanks
On the server-side just use:
const filename = 'test_download.xlsx';
// make sure to include the name and the extension of the file in the path
const filepath = 'your/path/to/the/file/test_download.xlsx';
/** filename is optional:
* if you don't pass it, the name of the file in the filepath will be used
* if you pass it the file at hte filepath will be downloaded with the name of `filename`
*/
res.download(filepath, filename);
This will return a blob to the client(make sure to include the correct headers for the response type) and then you can just save it or work with it with :
file = await axios.get('/dataexplorer/test',{ responseType: "blob"});
const ab = await file.data.arrayBuffer();
XLSX.read(Buffer.from(ab),{type:"buffer"})

How do you upload a blob base64 string to google cloud storage using Node.js

I'm building an application that will allow me to take a picture from my react app which accesses the web cam, then I need to upload the image to google cloud storage using a Hapi node.js server. The problem I'm encountering is that the react app snaps a picture and gives me this blob string (I actually don't even know if that's what it's called) But the string is very large and looks like this (I've shortened it due to it's really large size:
"imageBlob": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/...
I'm finding it hard to find resources that show me how to do this exactly, I need to upload that blob file and save it to a google cloud storage bucket.
I have this in my app so-far:
Item.postImageToStorage = async (request, h) => {
const image = request.payload.imageBlob;
const projectId = 'my-project-id'
const keyFilename = 'path-to-my-file'
const gc = new Storage({
projectId: projectId,
keyFilename: keyFilename
})
const bucket = gc.bucket('my-bucket.appspot.com/securityCam');
const blob = bucket.file(image);
const blobStream = blob.createWriteStream();
blobStream.on('error', err => {
h.response({
success: false,
error: err.message || '=-->' + err
})
});
console.log('===---> ', 'no errors::::')
blobStream.on('finish', () => {
console.log('done::::::', `https://storage.googleapis.com/${bucket.name}/${blob.name}`)
// The public URL can be used to directly access the file via HTTP.
const publicUrl = format(
`https://storage.googleapis.com/${bucket.name}/${blob.name}`
);
});
console.log('===---> ', 'past finish::::')
blobStream.end(image);
console.log('===---> ', 'at end::::')
return h.response({
success: true,
})
// Utils.postRequestor(path, payload, headers, timeout)
}
I ge to the success message/response h.response but no console logs appear except the ones outside of the blobStream.on I see all that start with ===---> but nothing else.
Not sure what I'm doing wrong, thanks in advance!
At the highest level, let us assume you want to write into file my-file.dat that is to live in bucket my-bucket/my-folder. Let us assume that the data you want to write is a binary chunk of data that is stored in a JavaScript Buffer object referenced by a variable called my_data. We would then want to code something similar to :
const bucket = gc.bucket('my-bucket/my-folder');
const my_file = bucket.file('my-file.dat');
const my_stream = my_file.createWriteStream();
my_stream.write(my_data);
my_stream.end();
In your example, something looks fishy with the value you are passing in as the file name in the line:
const blob = bucket.file(image);
I'm almost imagining you are thinking you are passing in the content of the file rather than the name of the file.
Also realize that your JavaScript object field called "imageBlob" will be a String. It may be that it indeed what you want to save but I can also imagine that what you want to save is binary data corresponding to your webcam image. In which case you will have to decode the string to a binary Buffer. This looks like it will be extracting the string data starting data:image/jpeg;base64, and then creating a Buffer from that by treating the string as Base64 encoded binary.
Edit: fixed typo

Download image GDrive API from browser

I try to retrieve all images within a google drive folder using their API. For now, I get all images as binary using this request:
const baseurl = "https://www.googleapis.com/drive/v3/files"
const query = "'XXX'+in+parents"
const token = "YYY"
fetch(`${baseurl}?q=${query}&key=${token}&fields=files(id)`).then(...)
And I get sth like:
But I can't figure out how to turn this into a <img ...>. I tried with btoa, it throws an exeption (that the string contains errors). I tried to transform the string to base64, but the final image is not valid. Any idea ?
I changed the approach. Instead of downloading the file and trying to decode it, I just extract a downloadable link from the response (webContentLink) and fill the src attribute of my <img ...>:
const baseurl = "https://www.googleapis.com/drive/v3/files"
const query = "'XXX'+in+parents"
const token = "YYY"
fetch(`${baseurl}?q=${q}&key=${key}&fields=files(webContentLink)`)
.then((data: any) => data.json())
.then((data: any) => data.files.map((f: any) => f.webContentLink))
...

Convert ICO icon file to PNG image file using plain Javascript

I want to..
.. convert an ICO file (e.g. http://www.google.com/favicon.ico ) to a PNG file after I downloaded it.
.. preserve transparency.
.. apply the solution in a node.js application.
I don't want to and already tried to ..
.. use native tools such as imagemagick (that's what I currently use in my application, but it's really bad for maintaining platform independency).
.. use tools that internally use native tools (e.g. gm.js).
.. rely on webservices such as http://www.google.com/s2/favicons?domain=www.google.de that don't allow configuring the resulting size or require payments or logins.
Therefore I'd love a Javascript-only solution. I used Jimp in another application, but it does not support ICO files.
Any help is appreciated. Thanks!
Use a FileReader() . Convert the Base64 to a data/png. Done.
const inputFile = __dirname + "/favicon.ico";
const outputFile = __dirname + "/favicon.png";
(function( inputFile, outputFile ) {
const fileApi = require("file-api");
const fs = require("fs");
const File = fileApi.File;
var fileReader = new fileApi.FileReader();
fileReader.readAsDataURL(new File(inputFile));
fileReader.addEventListener("load", function (ev) {
var rawdata = ev.target.result;
rawdata = rawdata.replace(/.*base64,/, "");
fs.writeFileSync(outputFile, rawdata, "base64");
});
})(inputFile, outputFile);
I am not familiar with Node environment but I wrote this ES6 module PNG2ICOjs using purely Javascript ArrayBuffer or Blob and can 100% run on client-side browsers (I assume Node file should act like a Blob).
import { PngIcoConverter } from "../src/png2icojs.js";
// ...
const inputs = [...files].map(file => ({
png: file
}));
// Result is a Blob
const resultBlob1 = await converter.convertToBlobAsync(inputs); // Default mime type is image/x-icon
const resultBlob2 = await converter.convertToBlobAsync(inputs, "image/your-own-mime");
// Result is an Uint8Array
const resultArr = await converter.convertAsync(inputs);

Categories

Resources