I am writing an addon in firefox that automatically sends the contents of a canvas to imgur. I have already built a similar extension in chrome, where it works as expected, so I know that the usage of imgurs API is correct. When I use the same approach in the Firefox addon, I always get this response:
{
"data": {
"error": "Image format not supported, or image is corrupt.",
"request": "/3/upload",
"method": "POST"
},
"success": false,
"status": 400
}
This is what I use to extract the image data and send it to the imgur API:
Request({
url: 'https://api.imgur.com/3/upload',
contentType : 'json',
headers: {
'Authorization': 'Client-ID ' + imgurClientID
},
content: {
type: 'base64',
key: imgurClientSecret,
name: 'neon.jpg',
title: 'test title',
caption: 'test caption',
image: getImageSelection('image/jpeg').split(",")[1]
},
onComplete: function (response) {
if (callback) {
callback(response);
} else {
var win = window.open(response['data']['link'], '_blank');
win.focus();
closeWindow();
}
}
}).post();
and this is used to get a selection from a canvas and get the dataurl of that selection:
function getImageSelection(type) {
//Create copy of cropped image
var mainImageContext = mainImage.getContext('2d');
var imageData = mainImageContext.getImageData(selection.x, selection.y, selection.w, selection.h);
var newCanvas = tabDocument.createElement("canvas");
newCanvas.width = selection.w;
newCanvas.height = selection.h;
newCanvas.getContext("2d").putImageData(imageData, 0, 0);
return mainImage.toDataURL(type)
}
I have tried everything: using the dataurl from the original canvas (mainImage), getting the dataUrl without any type, this: .replace(/^data:image\/(png|jpg);base64,/, "");
But imgur keeps complaining about bad format.
In the end, it turned out that the usage of the Request module of the Firefox addon SDK was wrong.
Instead of using contentType to provide the type of the content (like in jquery/ajax), you have to use dataType. See below:
Request({
url: 'https://api.imgur.com/3/upload',
dataType : 'json',
headers: {
'Authorization': 'Client-ID ' + imgurClientID
},
content: {
type: 'base64',
key: imgurClientSecret,
name: 'neon.jpg',
title: 'test title',
caption: 'test caption',
image: getImageSelection('image/jpeg', true)
},
onComplete: function (response) {
response = JSON.parse(response.text);
if (callback) {
callback(response);
} else {
var win = window.open(response['data']['link'], '_blank');
win.focus();
closeWindow();
}
}
}).post();
Related
Mobile application for upload image from Gallery / Camera , we need to ask run time permission.
If permission granted, we need to use.
const data = new FormData();
data.append("file", {
uri: file_parse_uri,
type: "image/jpeg",
name: file_parse_name,
});
headers: {
Authorization: 'if need',
"Content-Type": "multipart/form-data",
},
i think that you're performing the request wrong, try this instead :
Note : change the pickImage function so that the setUri takes (result.assets[0]) instead of (result.assets[0].uri)
const formBody = new FormData();
formBody.append('image', {
uri: uri.uri,
name: uri.name,
type: uri.type,
});
then instead of passing { image : uri } next to url try to passe this : { body: formBody }
Hello im new'ish in using and editing api's and im a bit stumped on TUI's Image Editor.
I'm trying to get the image data as a variable so that I can upload it separately to a website instead of just downloading it to the computer.
I am using this person's version of tui. I tried other methods as well but they didn't quite worked out for me.
const imageEditor = new tui.ImageEditor('#tui-image-editor-container', {
includeUI: {
loadImage: {
path: 'img/sampleImage2.png',
name: 'SampleImage',
},
theme: blackTheme, // or whiteTheme
initMenu: 'filter',
menuBarPosition: 'bottom',
},
cssMaxWidth: 700,
cssMaxHeight: 500,
usageStatistics: false,
});
window.onresize = function () {
imageEditor.ui.resizeEditor();
}
document.querySelector('#downloadButton').addEventListener('click', () => {
const myImage = instance.toDataURL();
document.getElementById("url").innerHTML = myImage;
});
</script>
<p id="url">Test</p>
Tried to change the code by using other guides but now it shows this error
Changed code
var imageEditor = new tui.ImageEditor('#tui-image-editor-container', {
includeUI: {
loadImage: {
path: 'img/sampleImage2.png',
name: 'SampleImage',
},
theme: blackTheme,
initMenu: 'filter',
menuBarPosition: 'left'
},
cssMaxWidth: 700,
cssMaxHeight: 1000,
usageStatistics: false
});
window.onresize = function() {
imageEditor.ui.resizeEditor();
}
function dataURLtoBlob(dataurl) {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {type:mime});
}
jQuery(document).ready(function ($) {
$('.tui-image-editor-download-btn').on('click', function (e) {
var blob = dataURLtoBlob(imageEditor.toDataURL());
var formData = new FormData();
formData.append('croppedImage', blob, 'sampleimage.png');
$.ajax({
url: '/files/upload_files/', // upload url
method: "POST",
data: formData,
success: function (data) {
alert('UPLOADED SUCCESSFULLY, PLEASE TRY AGAIN...');
},
error: function(xhr, status, error) {
alert('UPLOAD FAILED, PLEASE TRY AGAIN...');
}
});
return false;
});
});
</script>
Added in some false statements so that the object form can be sent.
jQuery(document).ready(function ($) {
$('.tui-image-editor-download-btn').on('click', function (e) {
var blob = dataURLtoBlob(imageEditor.toDataURL());
var formData = new FormData();
formData.append('croppedImage', blob, 'sampleimage.png');
$.ajax({
contentType: false, //added
processData: false, //added
url: '/files/upload_files/', // upload url
method: "POST",
data: formData,
success: function (data) {
alert('UPLOADED SUCCESSFULLY, PLEASE TRY AGAIN...');
},
error: function(xhr, status, error) {
alert('UPLOAD FAILED, PLEASE TRY AGAIN...');
}
});
return false;
});
});
I am trying to generate .bin file from from REST API written in Swing from AngularJS.Following is the code.
var options = {
url: 'http://example.com/imageAPI',
method: 'POST',
headers: {
'Authentication': headerAndPostParams[0],
'Content-Type': 'application/json',
'Accept': 'application/octet-stream'
},
responseType: 'arraybuffer',
data: {
uniqueId: headerAndPostParams[1],
imageName: headerAndPostParams[2],
clientMacAddress: headerAndPostParams[3]
}
};
return $http(options).then(function(sucessResponse) {
if (sucessResponse.data != "" && sucessResponse.data.responseCode === undefined) {
download(sucessResponse.data, "image.bin", "application/octet-stream");
return true;
}
return false;
});
Here are the response headers
Access-Control-Allow-Origin: http://localhost:8080
Content-Disposition:attachment;filename=cns3xxx_md_2.6.9_ac_aa_33_dd_aa_35.bin
Content-Length :7864320
Content-Type :application/octet-stream
Date :Tue, 18 Apr 2017 06:38:35 GMT
Vary :Origin
access-control-allow-credentials: true
Above code is working fine.But the issue is Image sent from API is of size 7.5 MB and the image generated from my UI side is of size 13.5 MB. Is there any decoding that we have to perform before giving it to donwload function. (NOTE: download is the function from donwload.js library.)
Found the solution. Actually $http service by default change the response to text. That doubles the size of image. To avoid it we need to add following parameter.
responseType: "blob"
$http({
url: 'http://example.com',
method: 'POST',
responseType: "blob",
headers: {
'Authentication': headerAndPostParams[0],
'Content-Type': 'application/json',
'Accept': 'application/octet-stream'
},
data: {
uniqueId: headerAndPostParams[1],
imageName: headerAndPostParams[2],
clientMacAddress: headerAndPostParams[3]
}
}).then(function(sucessResponse) {
if (sucessResponse.data != "" && sucessResponse.data.responseCode === undefined) {
var blob = new Blob([sucessResponse.data], {
type: "application/octet-stream"
});
download(blob, headerAndPostParams[2]);
return true;
}
return false;
}, function(response) {
return false;
});
I am developing multi-language website using Angularjs and a Web api as backend. I am trying to send RequestedPlatform and RequestedLanguage in the header whenever I make an API call.
Below is my Ajax request call.
$http.post(url,RegistrationData).then(function (response) {
var pageList = response.data.ID;
toastr.success('', 'Registered Succesfully');
$state.go('Registration.OTPVerification', { pageList });
}, function (error) {
toastr.error('', 'Error Occured');
});
updated code
var RegistrationData = {
FirstName: $scope.user.Fname,
LastName: $scope.user.Lname,
Password: $scope.user.password,
Gender: "Male",
DateOfBirth: "2017-04-04",
Nationality: $scope.user.selectedGlobe,
Mobile_CountryCod: "91",
MobileNumber: $scope.user.mobilenumber,
EmailId: $scope.user.email,
Home_Location: $scope.user.homeLocation,
Home_City: $scope.user.homeCity,
Home_Neighbourhood: $scope.user.homeNeighbourhood,
Home_HouseNumber: $scope.user.housenumber,
Home_MainStreet: $scope.user.homemainstreet,
Home_SubStreet: $scope.user.homesubstreet,
Work_Location: $scope.user.worklocation,
Work_City: $scope.user.workcity,
Work_Neighbourhood: $scope.user.workNeighbourhood,
Work_HouseNumber: $scope.user.workhousenumber,
Work_MainStreet: $scope.user.workmainstreet,
Work_SubStreet: $scope.user.worksubstreet
};
var req = {
method: 'POST',
url: url,
data: { RegistrationData: RegistrationData },
headers: {
RequestedPlatform: "Web",
RequestedLanguage: "English"
}
}
$http(req).then(function (response) {
var pageList = response.data.ID;
toastr.success('', 'Registered Succesfully');
$state.go('Registration.OTPVerification', { pageList });
}, function () {
toastr.error('', 'Error Occured');
});
May I get some help to set headers in Ajax. Any help would be appreciated.
you can send headers with headers property of $http
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': undefined
},
data: { test: 'test' }
}
$http(req).then(function(){...}, function(){...});
and if you want headers for all the requests that can be fully configured by accessing the $httpProvider.defaults.headers configuration object,
Reference
There are few ways and I have posted one which I have been using it for a while. I hope you are looking for the below
$http.post('test', data, {
withCredentials : false,
transformRequest : angular.identity,
headers : {
'Content-Type' : undefined
}
})
I'm developing a small function for an image-upload. This image-upload resizes selected pictures on the client and upload the resized image.
This works, but the browser will hang a lot between "resizes-functionality".
This is my code:
function manageImage(file) {
if (!file) return;
var mime = file.type;
var src = URL.createObjectURL(file);
loadImage.parseMetaData(file, function (data) {
var options = { maxWidth: 1920, maxHeight: 1920, canvas: true };
if (data.exif) {
options.orientation = data.exif.get('Orientation');
}
loadImage(file,
function (img, test) {
loaded++;
var formData = new FormData();
formData.append("image", dataURI);
$.ajax({
url: "/URL",
data: formData,
cache: false,
contentType: false,
processData: false,
async: false,
type: "POST",
success: function (resp) {
}
}).error(function () {
}).done(function () {
if (loaded < checkedFiles.length) {
manageImage(files[loaded]);
} else {
//FINISHED
}
});
},
options);
});
}
manageImage(files[0]);
This funcition is recursive, because i had some problems with the iteration (browser-hang, memory and cpu-usage).
Additionally, i'm using this library for EXIF-Data and correct orientation on mobile phones:
https://github.com/blueimp/JavaScript-Load-Image
With one or two selected pictures (e.g. 7MB) it works perfect, but i want to upload maybe 50 pictures.
It would be great if someone can give me a clue?!