Download an image using axios post request - javascript

I need base64 image chart from 'http://export.highcharts.com/'
getImg () {
const self = this;
axios.post('http://export.highcharts.com/', { options: self.$refs['lineChart'].options, type: 'image/png' }).then(function (response) {
base64.encode(response.data)
}).catch(function (e) {
console.log(e)
});
},

Here you can get image and convert it to base64. also similar to this question you can check the following link to get more information.
function getBase64(url) {
return axios
.get(url, {
responseType: 'arraybuffer'
})
.then(response => Buffer.from(response.data, 'binary').toString('base64'))
}

This works fine
getImg () {
const self = this;
axios.post('http://export.highcharts.com/', { options: self.$refs['lineChart'].options, type: 'image/png' }, { responseType: 'arraybuffer' }).then(function (response) {
let PNGBase64 = 'data:image/png;base64,' + Buffer.from(response.data, 'binary').toString('base64')
}).catch(function (e) {
console.log(e)
});
},

Related

My first api request always fails after page load

I'm having a problem with my API request that always fails after page load. Don't really know where Im wrong.
Here's my request and I call it when I interact with handleOpen function.
const stock = {
method: 'GET',
url: 'https://morningstar1.p.rapidapi.com/live-stocks/GetRawRealtimeFigures',
params: {Mic: props.mic, Ticker: clickedElement.ticker},
headers: {
'x-rapidapi-key': 'XXX',
'x-rapidapi-host': 'morningstar1.p.rapidapi.com'
}
}
const getStock = async () => {
try {
const res = await axios.request(stock);
return res.data;
}
catch (error) {
setOpen(false);
console.error("catch api error: ", error);
}
}
const handleOpen = name => {
let findClickedStock = props.stocksArray.find(item => item.ticker === name)
setClickedElement(findClickedStock)
getStock().then((dataFromStockApi) => {
let combined1 = { ...dataFromStockApi, ...findClickedStock }
setStockObject(combined1);
});
setOpen(true);
};
ERROR:
It's because your Ticker parameter is empty.
When you create "stock", clickedElement.ticker is undefined.
Do this:
// pass name in as a parameter
getStock(name).then(...)
Make getStock like like this:
const getStock = async (ticker) => {
try {
const res = await axios.request({
method: 'GET',
url: 'https://morningstar1.p.rapidapi.com/live-stocks/GetRawRealtimeFigures',
params: {Mic: props.mic, Ticker: ticker},
headers: {
'x-rapidapi-key': 'XXX',
'x-rapidapi-host': 'morningstar1.p.rapidapi.com'
}
});
return res.data;
}
catch (error) {
setOpen(false);
console.error("catch api error: ", error);
}
}

How can I print via blob in vue?

I try like this :
printBlob () {
this.$axios.get('/detail/1', {
responseType: 'blob'
}).then((response) => {
console.log('ok')
console.log(response.data)
const file = new Blob([response.data], { type: 'application/pdf' })
const fileURL = URL.createObjectURL(file)
window.open(fileURL)
}).catch((error) => {
console.log(error)
})
}
The result like this :
And the console log like this :
There is no data/response from the API
How can I solve this problem?

Display image from API

I got problem how to display image send by API from backend it not display. And when I console.log, I got this error.
This is my code as your reference.
HTML
<img [src]="imageToShow" style="width:100%;margin-left: -14px;">
Component
ngOnInit() {
this.getBanner()
}
getBanner() {
this.bannerId = {
confId: 1,
type: "Banner",
};
this.httpService.getBanner(this.bannerId).subscribe(
(baseImage: any) => {
let objectURL = "data:image/jpeg;base64," + baseImage.image;
this.imageToShow = this.sanitizer.bypassSecurityTrustUrl(objectURL);
},
(error) => {
// this.isImageLoading = false;
console.log(error);
}
);
}
Service
public getBanner(data){
console.log(data)
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
responseType: 'blob',
Authorization: 'Bearer '+this.getToken()
})
};
return this.httpClient.post((this.serverUrl + this.basePath + '/landing/conferenceitem'),data,httpOptions);
}
edit
when I check up Network Response I got this image
Try this
Step #1
Remove Content-Type header and set responseType to blob in httpOptions, but not in the header part like you did. Now, you should get a blob as a response. Before, angular was trying to parse your response as JSON, hence the error
public getBanner(data){
console.log(data)
const httpOptions = {
headers: new HttpHeaders({
Authorization: 'Bearer '+this.getToken()
}),
responseType: 'blob'
};
return this.httpClient.post((this.serverUrl + this.basePath + '/landing/conferenceitem'),data,httpOptions);
}
Step #2 Use baseImage instead of baseImage.image (the response is a blob, it does not have an image property), and then use createObjectURL to get an image url from the blob. Sanitize that URL like your did
this.httpService.getBanner(this.bannerId).subscribe(
(baseImage: Blob) => {
let objectURL = URL.createObjectURL(baseImage);
this.imageToShow = this.sanitizer.bypassSecurityTrustUrl(objectURL);
},
(error) => {
// this.isImageLoading = false;
console.log(error);
}
);
One way to fix this is by Setting the response type to blob
const requestOptions: Object = {
/* other options here */
responseType: 'blob'
}
return this.httpClient.post((this.serverUrl + this.basePath + '/landing/conferenceitem'),data,requestOptions);
and you have to convert your image data to a dataURL:
this.httpService.getBanner(this.bannerId).subscribe(
(baseImage: any) => {
this.imageToShow = baseImage;
},
(error) => {
// this.isImageLoading = false;
console.log(error);
}
);
Change Your getBannerMethod as below :-
getBanner() {
this.bannerId = {
confId: 1,
type: "Banner",
};
this.httpService.getBanner(this.bannerId).subscribe(
(baseImage: any) => {
const reader = new FileReader();
const url = reader.readAsDataURL(baseImage.image);
reader.onloadend = () => this.imageToShow = reader.result;
},
(error) => {
// this.isImageLoading = false;
console.log(error);
}
);
}
Working Stackblitz :- https://stackblitz.com/edit/angular-yvicvq

custom url in image upload jodit editor

I have implemented Jodit Editor (react)https://github.com/jodit/jodit-react, Insert Image option, in which can you upload the image, which saves to the default option by the Editor,
I would like to know how to use custom url and insert the image in editor
Jodit default behaviour
config:{
readonly: false,
enableDragAndDropFileToEditor: true,
uploader: { url: "https://xdsoft.net/jodit/connector/index.php?action=fileUpload"}
}
Expected
How to do adding custom url
config:{
readonly: false,
enableDragAndDropFileToEditor: true,
uploader: { url: "www.xyz.com/upload"}
}
In this repository, https://github.com/GilianMoa/jodit-editor-react
I'm uploading images with Cloudinary api.
Hope I can help you with this code.
I create a custom buttom:
uploadImageButton = () => {
Jodit.defaultOptions.controls.uploadImage = {
name: 'Upload image to Cloudinary',
iconURL: "https://www.kindpng.com/picc/m/261-2619141_cage-clipart-victorian-cloud-upload-icon-svg-hd.png",
exec: (async (editor) => {
await this.imageUpload(editor);
})
};
}
Then I create a method to open a dialog to pick the image and send to a service which send a post with the image file formData to cloudinary.
//dialog method
imageUpload = (editor) => {
const input = document.createElement('input');
input.setAttribute('type', 'file');
input.setAttribute('accept', 'image/*');
input.click();
input.onchange = async function () {
const imageFile = input.files[0];
if (!imageFile) {
return;
}
if (!imageFile.name.match(/\.(jpg|jpeg|png)$/)) {
return;
}
const imageInfo = await FileUpload(imageFile);;
this.insertImage(editor, imageInfo.url);
}.bind(this);
}
//this method insert the image inside the editor after the upload is done.
insertImage = (editor, url) => {
const image = editor.selection.j.createInside.element('img');
image.setAttribute('src', url);
editor.selection.insertNode(image);
}
// this method send the image to cloudinary
export const FileUpload = async (file) => {
let result = null;
let formData = new FormData();
formData.append('file', file);
formData.append('upload_preset', `${process.env.REACT_APP_CLOUDINARY_UPLOAD_PRESET}`);
await fetch(`https://api.cloudinary.com/v1_1/${process.env.REACT_APP_CLOUDINARY_CLOUD_NAME}/image/upload`, {
method: 'POST',
body: formData
})
.then((response) => response.json())
.then((data) => {
result = data;
})
.catch((error) => {
console.error('Error:', error);
});
return result;
}
I use jodit-react and upload img success ! the code is here hope to help you.
<JoditEditor
ref={this.editor}
value={'this.state.content'}
config={{
language: 'zh_cn',
toolbarButtonSize: 'large',
uploader: {
url: '/manage/upload', //your upload api url
insertImageAsBase64URI: false, not inster base64
imagesExtensions: ['jpg', 'png', 'jpeg', 'gif'],
//headers: {"token":`${db.token}`},
filesVariableName: function (t) {
return 'files[' + t + ']';
}, //"files",
withCredentials: false,
pathVariableName: 'path',
format: 'json',
method: 'POST',
prepareData: function (formdata) {
return formdata;
},
isSuccess: function (e) {
debugger;
return e.success;
},
getMessage: function (e) {
return void 0 !== e.data.messages && Array.isArray(e.data.messages)
? e.data.messages.join('')
: '';
},
process: function (resp: any) { //success callback transfrom data to defaultHandlerSuccess use.it's up to you.
let files = [];
files.unshift(resp.data);
return {
files: resp.data,
error: resp.msg,
msg: resp.msg,
};
},
error: function (this: any, e: Error) {
this.j.e.fire('errorMessage', e.message, 'error', 4000);
},
defaultHandlerSuccess: function (this: Uploader, resp: IUploaderData) { // `this` is the editor.
const j = this;
debugger;
if (resp.files && resp.files.length) {
const tagName = 'img';
resp.files.forEach((filename: string, index: number) => { //edetor insertimg function
const elm = j.createInside.element(tagName);
elm.setAttribute('src', filename);
j.s.insertImage(elm as HTMLImageElement, null, j.o.imageDefaultWidth);
});
}
},
defaultHandlerError: function (this: any, e) {
this.j.e.fire('errorMessage', e.message);
},
contentType: function (e) {
return (
(void 0 === this.jodit.ownerWindow.FormData || 'string' == typeof e) &&
'application/x-www-form-urlencoded; charset=UTF-8'
);
},
},
}}
/>
I have test ok.

Redux Thunk - Change state before REST request

I am quite new to Redux Thunk and have an issue that I want to update a contract with a 'FileList' (file appendix), but if I use JSON.stringify the file will have a 0 value. If I convert the file to Base64 this problem is solved, but the PUT request is performed before the file is converted.
I searched a lot about Redux Thunk and think it might be some issue with Dispatch, I tried quite a lot and didn't become much wiser. Most of the things that I tried returned: "Actions must be plain objects. Use custom middleware for async actions."
Would appreciate some help or some search suggestions..
ps. contract.answers[0].answer[0] is the file. This acquires some refactoring, but first it needs to work.
const toBase64 = (file) => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = (error) => reject(error);
});
export function updateContract(contract) {
const base64File = toBase64(contract.answers[0].answer[0]);
base64File.then((value) => {
contract.answers[0].answer[0] = value; //Set file as base64
});
return {
type: SAVE,
fetchConfig: {
uri: contract._links.self,
method: 'PUT',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(contract), // Does not handle files
failureHandler(error) {
const {
details,
status,
} = error;
// If the contract was invalid, throw form errors:
if (status.code === 400 && details) {
// Map the question ids to fields:
throw new SubmissionError(Object.keys(details).reduce(
(acc, questionId) => {
acc[`question${questionId}`] = details[questionId];
return acc;
},
{},
));
}
return {
type: SAVE_FAILURE,
error,
};
},
successHandler(json) {
return {
type: SAVE_SUCCESS,
data: json,
};
},
},
};
}
Kind regards,
Gust de Backer
This happen because toBase64 return a Promise and itself is async, so in your case is necessary encapsule inside a new then.
export function updateContract(contract) {
const base64File = toBase64(contract.answers[0].answer[0]);
base64File.then((value) => {
contract.answers[0].answer[0] = value; //Set file as base64
});
return (dispatch) => {
base64File.then(() => dispatch({
type: SAVE,
fetchConfig: {
uri: contract._links.self,
method: 'PUT',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(contract), // Does not handle files
failureHandler(error) {
const {
details,
status,
} = error;
// If the contract was invalid, throw form errors:
if (status.code === 400 && details) {
// Map the question ids to fields:
throw new SubmissionError(Object.keys(details).reduce(
(acc, questionId) => {
acc[`question${questionId}`] = details[questionId];
return acc;
}, {},
));
}
return {
type: SAVE_FAILURE,
error,
};
},
successHandler(json) {
return {
type: SAVE_SUCCESS,
data: json,
};
},
},
}))
};
}
Yes, the redux accept a function as return, that function receive a dispatch on params, you can use it to dispatch the request after convert is ready :)

Categories

Resources