Download Video using node js - node.js

I have one link, It's local, so this link if I write the link directly in chrome a video is downloaded.
this is the link https://127.0.0.1:7001/api/media/getDirectDownloadVideo?username=admin&password=admin*&setCookie=true&camera_id={c22128b3-6af0-79b8-764e-62234dd023fc}&pos=2023-01-23T13:30&duration=10
so I just want to implementate one function to get it, through node js, I'm using fetch, I create this function:
exports.getVideo = async (req, res) => {
const path = process.env.APP_LOCALHOST_URL + urlDirectDownloadVideo(req.query);
const response = await fetch(path,{
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${req.query.token}`
},
});
return await response.json();
}
currently don't download the video, what I have to do? to downloaded it

Related

Upload image to a nodeJs server using react-native

I want to upload an image from react-native (cli without expo) to a node server, i tried using axios with formData filed is not recognised by multer, then i tried with fetch that worked image was stored in server but i get promise rejection on front:
const postDocument = (doc) => {
//i used react-native-document-picker to pick document(doc) i logged it and it works
const url =`${api}/sendImage`;
const formData = new FormData();
const id = uuid.v4()
formData.append('id',id)
formData.append('image', doc);
const options = {
method: 'POST',
body: formData,
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
};
fetch(url, options).then((res)=>{
//getting promise rejection even without code but image is stored in backend
}).catch(error=>{})
}
getting this error : [TypeError: Network request failed]
using rn-fetch-blob (react-native-cli not expo-cli) instead of fetch or axios solved this for me

How do I send progress streams using Node and Express?

I am making a Video Resizer site and I need to send the video conversion progress to the user. I read about SSE but all tutorials use get request and listen through EventSource.
In my case it is post request which contains the video file to be resized.
My Server Side Code is
const resizeVideo = async (req, res) => {
const command = ffmpeg(path.join(rootPath, 'uploads', 'videos', 'v.mp4'));
command.size('?x480').keepDAR().on('end', () => {
res.end();
console.log("Converted");
}).on('progress', function (progress) {
console.log('Processing: ' + progress.percent + '% done');
// I want to send this progress updates to react.js client.
}).save(path.join(rootPath, 'output', '1.mp4'));
}
My Client Side code is
setIsUploading(true);
const config: AxiosRequestConfig = {
responseType: 'json',
headers: {
'Content-Type': 'multipart/form-data', 'Access-Control-Allow-Origin': 'http://localhost:3000', 'Access-Control-Allow-Methods': 'POST', 'Access-Control-Allow-Headers': 'Content-Type, Authorization'
},
};
const response = await instance.post('videoconvert/resize', formData, config);
//I want to get updates here.
setIsUploading(false);
How do I achieve that?
you cant use axios you need to use SocketIO to send update live

Get image from Axios and send as Form Data to Wordpress API in a Cloud Function

What I'm trying to accomplish is using a Firebase Cloud Function (Node.js) to:
First download an image from an url (f.eg. from unsplash.com) using an axios.get() request
Secondly take that image and upload it to a Wordpress site using the Wordpress Rest API
The problem seems (to me) to be that the formData doesnt actually append any data, but the axios.get() request actually does indeed retrieve a buffered image it seems. Maybe its something wrong I'm doing with the Node.js library form-data or maybe I get the image in the wrong encoding? This is my best (but unsuccessfull) attempt:
async function uploadMediaToWordpress() {
var FormData = require("form-data");
var formData = new FormData();
var response = await axios.get(
"https://images.unsplash.com/photo-1610303785445-41db41838e3e?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=634&q=80"
{ responseType: "arraybuffer" }
);
formData.append("file", response.data);
try {
var uploadedMedia = await axios.post("https://wordpresssite.com/wp-json/wp/v2/media",
formData, {
headers: {
"Content-Disposition": 'form-data; filename="example.jpeg"',
"Content-Type": "image/jpeg",
Authorization: "Bearer <jwt_token>",
},
});
} catch (error) {
console.log(error);
throw new functions.https.HttpsError("failed-precondition", "WP media upload failed");
}
return uploadedMedia.data;
}
I have previously successfully uploaded an image to Wordpress with Javascript in a browser like this:
async function uploadMediaToWordpress() {
let formData = new FormData();
const response = await fetch("https://images.unsplash.com/photo-1610303785445-41db41838e3e?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=634&q=80");
const blob = await response.blob();
const file = new File([blob], "image.jpeg", { type: blob.type });
formData.append("file", file);
var uploadedMedia = await axios.post("https://wordpresssite.com/wp-json/wp/v2/media",
formData, {
headers: {
"Content-Disposition": 'form-data; filename="example.jpeg"',
"Content-Type": "image/jpeg",
Authorization: "Bearer <jwt_token>",
},
});
return uploadedMedia.data;
},
I have tried the last couple of days to get this to work but cannot for the life of me seem to get it right. Any pointer in the right direction would be greatly appreciated!
The "regular" JavaScript code (used in a browser) works because the image is sent as a file (see the new File in your code), but your Node.js code is not really doing that, e.g. the Content-Type value is wrong which should be multipart/form-data; boundary=----...... Nonetheless, instead of trying (hard) with the arraybuffer response, I suggest you to use stream just as in the axios documentation and form-data documentation.
So in your case, you'd want to:
Set stream as the responseType:
axios.get(
'https://images.unsplash.com/photo-1610303785445-41db41838e3e?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=634&q=80',
{ responseType: 'stream' }
)
Use formData.getHeaders() in the headers of your file upload request (to the /wp/v2/media endpoint):
axios.post( 'https://wordpresssite.com/wp-json/wp/v2/media', formData, {
headers: {
...formData.getHeaders(),
Authorization: 'Bearer ...'
},
} )
And because the remote image from Unsplash.com does not use a static name (e.g. image-name.jpg), then you'll need to set the name when you call formData.append():
formData.append( 'file', response.data, 'your-custom-image-name.jpeg' );
I hope that helps, which worked fine for me (using the node command for Node.js version 14.15.4, the latest release as of writing).

TypeScript CLI: How to save octect-stream response from node-fetch call to Get Request?

I am making a Get Request using Node-Fetch to a web api. It returns octet-stream response to be saved as a file in a local.
I tried using downloadjs (download()) and download.js (downloadBlob()), but both of them did not work.
downloadBlob() returned "createObjectURL is not a function" error, and download() returned "window is not defined at object." error.
The call is below
let res = await fetch(apiURL, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
}
})
I think I am completely lost here. What should I do to download the file to local drive? How should I construct .then block here?
downloadjs and download.js won't help because these are front end libraries that trigger the download process in a browser. For instance, when you generate an image on the client (in browser) and want a user to download it.
In order to save an octet-stream in Node(CLI) you can use fs module:
const data = await fetch(apiURL, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
}
}).then(res => res.buffer());
fs.writeFile('filename.dat', data, (err) => {
if (err) throw err;
console.log('The file has been saved!');
});

Node JS upload file streams over HTTP

I'm switching one of my projects from request over to something a bit more light-weight (such as got, axios, or fetch). Everything is going smoothly, however, I'm having an issue when attempting to upload a file stream (PUT and POST). It works fine with the request package, but any of the other three return a 500 from the server.
I know that a 500 generally means an issue on the server's end, but it is consistent only with the HTTP packages that I'm testing out. When I revert my code to use request, it works fine.
Here is my current Request code:
Request.put(`http://endpoint.com`, {
headers: {
Authorization: `Bearer ${account.token.access_token}`
},
formData: {
content: fs.createReadStream(localPath)
}
}, (err, response, body) => {
if (err) {
return callback(err);
}
return callback(null, body);
});
And here is one of the attempts using another package (in this case, got):
got.put(`http://endpoint.com`, {
headers: {
'Content-Type': 'multipart/form-data',
Authorization: `Bearer ${account.token.access_token}`,
},
body: {
content: fs.createReadStream(localPath)
}
})
.then(response => {
return callback(null, response.body);
})
.catch(err => {
return callback(err);
});
Per the got documentation, I've also tried using the form-data package in conjunction with it according to its example and I still get the same issue.
The only difference between these 2 I can gather is with got I do have to manually specify the Content-Type header otherwise the endpoint does give me a proper error on that. Otherwise, I'm not sure how the 2 packages are constructing the body with the stream, but as I said, fetch and axios are also producing the exact same error as got.
If you want any of the snippets using fetch or axios I'd be happy to post them as well.
I know this question was asked a while ago, but I too am missing the simple pipe support from the request package
const request = require('request');
request
.get("https://res.cloudinary.com/demo/image/upload/sample.jpg")
.pipe(request.post("http://127.0.0.1:8000/api/upload/stream"))
// Or any readable stream
fs.createReadStream('/Users/file/path/localFile.jpeg')
.pipe(request.post("http://127.0.0.1:8000/api/upload/stream"))
and had to do some experimenting to find similar features from current libraries.
Unfortunately, I haven't worked with "got" but I hope the following 2 examples help someone else that are interested in working with the Native http/https libraries or the popular axios library
HTTP/HTTPS
Supports piping!
const http = require('http');
const https = require('https');
console.log("[i] Test pass-through: http/https");
// Note: http/https must match URL protocol
https.get(
"https://res.cloudinary.com/demo/image/upload/sample.jpg",
(imageStream) => {
console.log(" [i] Received stream");
imageStream.pipe(
http.request("http://localhost:8000/api/upload/stream/", {
method: "POST",
headers: {
"Content-Type": imageStream.headers["content-type"],
},
})
);
}
);
// Or any readable stream
fs.createReadStream('/Users/file/path/localFile.jpeg')
.pipe(
http.request("http://localhost:8000/api/upload/stream/", {
method: "POST",
headers: {
"Content-Type": imageStream.headers["content-type"],
},
})
)
Axios
Note the usage of imageStream.data and that it's being attached to data in the Axios config.
const axios = require('axios');
(async function selfInvokingFunction() {
console.log("[i] Test pass-through: axios");
const imageStream = await axios.get(
"https://res.cloudinary.com/demo/image/upload/sample.jpg",
{
responseType: "stream", // Important to ensure axios provides stream
}
);
console.log(" [i] Received stream");
const upload = await axios({
method: "post",
url: "http://127.0.0.1:8000/api/upload/stream/",
data: imageStream.data,
headers: {
"Content-Type": imageStream.headers["content-type"],
},
});
console.log("Upload response", upload.data);
})();
Looks like this was a headers issue. If I use the headers directly from FormData (i.e., headers: form.getHeaders()) and just add in my additional headers afterwards (Authorization), then this ends up working just fine.
For me just works when I added other parameters on FormData.
before
const form = new FormData();
form.append('file', fileStream);
after
const form = new FormData();
form.append('file', fileStream, 'my-whatever-file-name.mp4');
So that way I can send stream from my backend to another backend in node, waiting a file in multipart/form-data called 'file'

Resources