Persist download progress angularjs buffered response - javascript

I am downloading some file with $http which is calling java rest API, it responds in buffered array. I have to persist the download even if the browser reloaded. I am not sure whether it is possible or not within the client side itself.
Here is my code :
$http({
url : downloadUrl,
method : 'POST',
data : {filePath : path},
cache: true,
headers : {
'Content-type' : 'application/json',
'Accept': 'application/zip'
},
eventHandlers: {
progress: function (e) {
console.log('Progress :'+((e.loaded /
itemSelected.fileSize) * 100));
}
},
responseType : 'arraybuffer'
}).then(function (res) {
var blob = new Blob([res.data], {type:"application/octet-
stream"});
var filename = test.zip;
// using filesaver to download the file from blob
FileSaver.saveAs(blob, filename);
}, function (err) {
console.log(err);
});

Related

upload video to bunny stream with axios

i need to upload video to bunny stream :bunny docs
i convert file to base64 as thy do here: upload file: BODY PARAMS
if you select js axios as LANGUAGE you'll see the data value set in base64
and this is my code:
function UploadVideo(e){
const data = new FormData();
let file = e.target.files[0];
let video;
const toBase64 = file => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
async function Main() {
video = await toBase64(file);
}
Main();
const c_options = {
method: 'POST',
url: 'https://video.bunnycdn.com/library/49034/videos',
headers: {
Accept: 'application/json',
'Content-Type': 'application/*+json',
AccessKey: ''
},
data: '{"title":"test"}'
};
axios.request(c_options).then(function (c_response) {
//upload start
const u_options = {
method: 'PUT',
url: `https://video.bunnycdn.com/library/49034/videos/${c_response.data.guid}`,
headers: {
Accept: 'application/json',
AccessKey: ''
},
data: video,
};
axios.request(u_options).then(function (u_response) {
//post url to php
console.log(u_response.data);
}).catch(function (error) {
console.error(error);
});
//upload end
console.log(c_response.data);
}).catch(function (error) {
console.error(error);
});
}
but it return status code 400
The 400 error text: "Failed to read the request form. Form key length limit 2048 exceeded."
how can i do that?
The error is telling that a key is too long.
Your data property is meant to be an object, because axios default Content-Type (which you have omitted) is application/x-www-form-urlencoded.
If you want to send the file, then you need to set the Content-Type in you header to Content-Type: application/octet-stream, i.e. your header object should be
headers: {
Accept: 'application/json',
AccessKey: '',
Content-Type: 'application/octet-stream'
},
This shown in the javascript example on the bunny.net page you link to.

How to download ZIP file from reactjs using post api?

How to download zip file from reactjs using POST API.
The request is coming from nodejs in binary form
you can use jszip link https://github.com/Stuk/jszip like
import zipTargetFiles from '/path'
zipTargetFiles( data ).then(file => {
//operations
})
if you use fetch like this.
fetch('URL', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
//Body
})
}).then((response)=>{
//here is youu want zip data
var zip = new JSZip();
var zipData = response.data //
// Add an top-level, arbitrary text file with contents
zip.file("response.txt", zipData);
// Generate the zip file asynchronously
zip.generateAsync({type:"blob"})
.then(function(content) {
// Force down of the Zip file
saveAs(content, "zipFile.zip");
});
}).catch((error)=>{
console.log(error)
})
You can use JsZip on Client Side. Then, do a request with axios. Like this:
request = (currentUrl: string): Promise<void> => axios({
url: currentUrl,
method: 'GET',
responseType: 'blob',
}).then((response) => {
const url: string = window.URL.createObjectURL(new Blob([response.data]));
});

Download Ajax response as zip file?

I am trying to download multiple images as a zip file. As I am using Azure blob, first I listed all blobs then compressed it using Archiver and used pipe function to send it to the client. But I am getting zip as a raw file and it is not downloading. I am using Node js + Express.
Server-side script:
function zipURLs(urls, outStream) {
var zipArchive = archiver.create('zip');
async.eachLimit(urls, 3, function(url, done) {
console.log(url);
var stream = request.get(url);
stream.on('error', function(err) {
return done(err);
}).on('end', function() {
return done();
});
// Use the last part of the URL as a filename within the ZIP archive.
zipArchive.append(stream, { name : url.replace(/^.*\//, '') });
}, function(err) {
if (err) throw err;
zipArchive.finalize();
zipArchive.pipe(outStream);
});
}
var data = {};
data.blob_name = value;
console.log('downloading');
$.ajax({
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json',
url: 'download/',
success: function(data) { console.log(data); }
Outstream is res. So I get data like this:-
How can I download directly as zip file using js?
Thanks
There is a lot that goes into using ajax to download a file, first you have to be able to access the data in binary(not text which is the default) by setting the responseType to blob.
Then you have to use actually get a way to get the download dialog to show up, below you can see the anchor with download attribute technique.
jQuery.ajax({
url:'download/',
type:'POST',
data: JSON.stringify(data),
contentType: 'application/json',
xhrFields:{
responseType: 'blob'
},
success: function(data){
var anchor = document.getElementById('a');
var url = window.URL || window.webkitURL;
anchor.href = url.createObjectURL(data);
anchor.download = 'archive.zip';
document.body.append(anchor);
anchor.click();
setTimeout(function(){
document.body.removeChild(anchor);
url.revokeObjectURL(anchor.href);
}, 1};
},
error:function(){
}
});
requires jQuery3+

How to convert the string type from an API response to an image file - ����\u0000\u0010JFIF\u0000\u0001\u0001\u0000\u0000\u0001 -

I have used https://graph.microsoft.com/beta/me/photo/$value API to get the profile picture of the outlook user. I get an image on running the above API in the rest-client. The content-type of the API is "image/jpg"
But, in Node.js, the response of the API is as follows:
����\u0000\u0010JFIF\u0000\u0001\u0001\u0000\u0000\u0001\u0000\u0001\u0000\u0000��\u0000�\u0000\u0005\u0005\u0005\u0005\u0005\u0005\u0006\u0006\u0006\u0006\b\t\b\t\b\f\u000b\n\n\u000b\f\u0012\r\u000e\r\u000e\r\u0012\u001b\u0011\u0014\u0011\u0011\u0014\u0011\u001b\u0018\u001d\u0018\u0016\u0018\u001d\u0018+"\u001e\u001e"+2*(*2<66<LHLdd�\u
I used 'fs' to create an image file. The code is as follows:
const options = {
url: "https://graph.microsoft.com/beta/me/photo/$value",
method: 'GET',
headers: {
'Accept': 'application/json',
'Authorization': `Bearer ${locals.access_token}`,
'Content-type': 'image/jpg',
}
};
request(options, (err, res, body) => {
if(err){
reject(err);
}
console.log(res);
const fs = require('fs');
const data = new Buffer(body).toString("base64");
// const data = new Buffer(body);
fs.writeFileSync('profile.jpg', data, (err) => {
if (err) {
console.log("There was an error writing the image")
}
else {
console.log("The file is written successfully");
}
});
});
The file is written successfully, but the .jpg image file generated is broken. I am unable to open the image.
The output of the image file is as follows:
77+977+977+977+9ABBKRklGAAEBAAABAAEAAO+/ve
You can do this by streaming the response like this,
request(options,(err,res,body)=>{
console.log('Done!');
}).pipe(fs.createWriteStream('./profile.jpg'));
https://www.npmjs.com/package/request#streaming
https://nodejs.org/api/fs.html#fs_class_fs_writestream
The reason for this is that by default, request will call .toString() on the response data. In case of binary data, like a RAW JPEG, this isn't what you want.
It's also explained in the request documentation (albeit vaguely):
(Note: if you expect binary data, you should set encoding: null.)
Which means that you can use this as well:
const options = {
encoding : null,
url : "https://graph.microsoft.com/beta/me/photo/$value",
method : 'GET',
headers : {
'Accept' : 'application/json',
'Authorization' : `Bearer ${locals.access_token}`,
'Content-type' : 'image/jpg',
}
};
However, streaming is probably still the better solution, because it won't require the entire response being read into memory first.
Request is deprecated. You can do this with axios;
// GET request for remote image in node.js
axios({
method: 'get',
url: 'http://example.com/file.jpg',
responseType: 'stream'
})
.then(function (response) {
response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});

angular and Cloudinary direct upload 400 (Bad Request)

i'm getting a 400 bad request error when trying to upload to cloudinary with the following code:
var file = /* your file */;
var cloud_name = 'your cloud_name';
var fd = new FormData();
fd.append('upload_preset', 'seller');
fd.append('file', file);
$http
.post('https://api.cloudinary.com/v1_1/' + cloud_name + '/image/upload', fd, {
headers: {
'Content-Type': application/x-www-form-urlencoded,
'X-Requested-With': 'XMLHttpRequest'
}
})
.success(function (cloudinaryResponse) {
// do stuff with cloudinary response
// cloudinaryResponse = { public_id: ..., etc. }
})
.error(function (reponse) {
});
What am I missing? Is it possible to do a Cloudinary direct upload?

Categories