FileSaver.js is saving corrupt images - http

This was working fine and suddenly stopped working. I'm not sure what exactly changed.
I need to download multiple images via URLs.
I'm using the following code:
https://plnkr.co/edit/nsxgwmNYUAVBRaXgDYys?p=preview
$http({
method:"GET",
url:"imageurl"
}).then(function(response){
saveAs(new Blob([response.data]), "image.jpg");
},function(err){
});
The files have different sizes, they are not 0 bytes.

For others coming here, check this solution.
What needed to be done was to add responseType: "blob" to the request:
$http({
method:"GET",
url:"imageurl",
responseType: "blob"
})
.then(...)
Here is the documentation for the responseType valid values, where it says the default is "" so the response is treated as text:
"": An empty responseType string is treated the same as "text", the default type (therefore, as a DOMString).
"blob:": The response is a Blob object containing the binary data.

Following code worked for me:
axios.get(`http://localhost:61078/api/values`, {
responseType: 'blob',
}).then(response => {
if (response) {
var FileSaver = require('file-saver');
FileSaver.saveAs(new Blob([response.data]), "image.png");
}
});

Related

Mirage Passthrough returns Response Object instead of JSON data returned from network call

I am getting an error:
Mirage: Your Ember app tried to GET 'http://localhost:3006/data.json',
but there was no route defined to handle this request.
Define a route that matches this path in your mirage/config.js file.
Did you forget to add your namespace?
So following the documentation of mirage i added this:
this.passthrough('http://localhost:3006/data.json');
Even though after adding passthrough, I am getting such Response instead of JSON Object returned from the network api call.
The Actual Request i am making is:
fetch(`${host}/data.json`)
.then(res => res.json())
.then(data => {
// my operation on data
});
The response i am getting is:
{bodyUsed: true
headers: Headers {map: {…}}
ok: true
status: 200
statusText: "OK"
type: "default"
url: "http://localhost:3006/data.json"
_bodyInit: null
_bodyText: ""}
But I am expecting:
{
"files":
{
"x": "any",
"a": "any",
"b": "any",
"c": "any"
}
}
I kept a debugger in Pretender.js which is sending the FakeRequest and there in its object, I see that FakeRequest has responseType="" and response as null. And somehow my responseText has value but that is not considered and response value is considered and receiving null.
Also there is a logic which is return saying
"response" in xhr ? xhr.response : xhr.responseText
In this case i have response property but its value is null. Hence according to the above condition it is returning xhr.response which is null
Thanks in Advance.

Upload file size limit with custom webscript on Alfresco Community 5.2

I need help to upload document content back in Alfresco Community 5.2 though a share javascript.
The destination noderef is already existing, I upload a new version of a document.
I can't use the api/upload web service because I also need to do some operation on the noderef and I have a base64 content of the file which need to be converted.
So I wrote a new webscript and it is all working fine, at least while I upload documents which are smaller than 3MB,
Here it is the code
Alfresco.util.Ajax.request({
method: Alfresco.util.Ajax.POST,
dataObj: {
bytes: response.bytes,
digestAlgorithm: response.digestAlgorithm,
mimeType: response.mimeType.mimeTypeString,
name: response.name,
nodeRef: this.nodeRef,
signatureLevel: this.signatureLevel
},
url: thisClass.urlAlfrescoService + "myOrg/myPackage/uploadDocument",
successCallback: {
fn: thisClass._successOnUploadContent,
scope: this
},
failureCallback: {
fn: thisClass._errorOnUploadContent,
scope: this
},
scope: this,
noReloadOnAuthFailure: true
});
Do I miss some option to increase max upload file size?
I tryed uploading the file normally (with drag and drop) and it works.
The problem is when the file is >= 3MB the java class behind the webscript does not receive any byte
UPDATE
After some researches I found it could be a problem of how data are passed through POST, as application/x-www-form-urlencoded instead of multipart/form-data, but I can't find a way to specify the request content type in the ajax request
SOLUTION
The problem was the application/x-www-form-urlencoded instead of the multipart/form-data, I used a fetch POST request as stated here, but also the ajax request solution is good.
Last week,I had a same very similar problem with Alfresco AJAX request on Alfresco 5.0.2.5 and I used jquery's AJAX calls and it worked for me.
$.ajax({
url: Alfresco.constants.PROXY_URI + "your_web_script",
type: "POST",
data: dataFromFiles,
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData: false,
dataType: "text",
success: function(data, textStatus, jqXHR) {
},
error: function(jqXHR, textStatus, errorThrown) {
}
});
Reference link : https://blog.arvixe.com/sending-multipart-form-using-ajax/
Hope this helps you.

Error while instanciating Restivus "Cannot find name 'Restivus' "

I imported restivus using :
meteor add nimble:restivus
And while using Restivus I encounter this error on meteor startup :
"Cannot find name 'Restivus' ".
I can although GET requests but I wonder if it impacts the behavior of the app.
Here is the code used :
if (Meteor.isServer) {
// Global API configuration
var Api = new Restivus({
apiPath: 'api/',
prettyJson: true
});
}
When receiving POSTs my request.body and my bodyParams are empty :
Api.addRoute(':id/test', {
post: function () {
var id = this.urlParams.id;
console.log("Body contains : ");
console.log(this.bodyParams);
return {
status: 'success',
url : 'post test from id: '+id,
body : this.bodyParams
};
}
});
Does anyone know how to make this error disappear and if this is linked to the POST body problem ?
If you use Meteor 1.4+ you can try to import Restivus to your file with something like this:
import Restivus from 'nibmle:restivus';
The problem with post body being empty was caused by the request I made :
I wasn't specifying the Content-type header.
Once I specified the "Content-Type": "application/json" it worked.
The "Cannot find 'Restivus' " Error is still here though.
Your code looks ok. Here is some code from a server-only file that I am using:
// Global API configuration
var Api = new Restivus({
useDefaultAuth: true,
prettyJson: true,
apiPath: 'restAPI/',
defaultHeaders: { 'Content-Type': 'application/json;encoding="UTF-8"' }
});
// Generates: GET, POST on /api/items and GET, PUT, DELETE on
// /api/items/:id for the Items collection
Api.addCollection(Policy);
Perhaps you should move your code to the server directory? I am on Meteor 1.3.4.

meteor autocomplete server-side

I'm writing a meteor app and I'm trying to add an autocomplete feature to a search box. The data is very large and is on the server, so I can't have it all on the client. It's basically a database of users. If I'm not wrong, the mizzao:autocomplete package should make that possible, but I can't seem to get it to work.
Here's what I have on the server:
Meteor.publish('autocompleteViewers', function(selector, options) {
Autocomplete.publishCursor(viewers.find(selector, options), this);
this.ready();
});
And here are the settings I use for the search box on the client:
getSettings: function() {
return {
position: 'bottom',
limit: 5,
rules: [{
subscription: 'autocompleteViewers',
field: '_id',
matchAll: false,
options: '',
template: Template.vLegend
}],
};
}
But I keep getting this error on the client:
Error: Collection name must be specified as string for server-side search at validateRule
I don't really understand the problem. When I look at the package code, it just seems like it's testing whether the subscription field is a string and not a variable, which it is. Any idea what the problem could be? Otherwise is there a minimum working example I could go from somewhere? I couldn't find one in the docs.
Error: Collection name must be specified as string for server-side search at validateRule
You get this error because you don't specify a Collection name in quotes.
getSettings: function() {
return {
position: 'bottom',
limit: 5,
rules: [{
subscription: 'autocompleteViewers',
field: '_id',
matchAll: false,
collection: 'viewers', // <- specify your collection, in your case it is a "viewers" collection.
options: '',
template: Template.vLegend
}],
};
}
For more information please read here.
Hope this helps!

How to include User-Agent info in a Meteor.http.call? MediaWiki requires it

Whenever I call the below method (CoffeeScript) that is on the server I get "Scripts should use an informative User-Agent string with contact information, or they may be IP-blocked without notice" from Wikipedia. How do I include user-agent info in the call? Or does it grab this from Meteor Accounts (which I'm not using yet)? thank you for any help...
Meteor.methods
wpSearch: (queryStr) ->
result = Meteor.http.call "GET", "http://en.wikipedia.org/w/api.php",
params:
action: "query"
list: "search"
format: "json"
srwhat: "text"
srsearch: queryStr
To clarify the previous answer for future visitors, the syntax for Meteor.http.get is as follows:
result = Meteor.http.get("https://api.github.com/user", {
headers: {
"User-Agent": "Meteor/1.0"
},
params: {
access_token: accessToken
}
});
Note the curly braces around the headers option and the comma afterwards separating the headers and params options (it's a syntax error without these things). This is example is part of the EventedMind how-to to customize the loginButtons during the onCreateUser() callback.
Just set User-Agent in the headers parameter (see http://docs.meteor.com/#meteor_http)
Meteor.methods
wpSearch: (queryStr) ->
result = Meteor.http.call "GET", "http://en.wikipedia.org/w/api.php",
headers:
"User-Agent": "Meteor/1.0"
params:
action: "query"
list: "search"
format: "json"
srwhat: "text"
srsearch: queryStr

Resources