Send json object as body in a POST request - json

I develop a project in Angular 9 which reads a csv file and send its content to the server.
I have a model for the file's records.
The request shows the object in "Request payload" but when it get to the API conntroller the data doesn't recognized as [FromBody] parameter.
Do you have any solution for me?
This is my code:
Model:
export class CSVRecord {
public code: string;
public date: Date;
public value: number;
public period: string;
}
Type script:
export class AppComponent {
title = 'FastWayToSerieses-Client';
constructor(public apiService: ApiService, private http: HttpClient ) {
}
public records: any[] = [];
#ViewChild('csvReader') csvReader: any;
uploadListener($event: any): void {
const text = [];
const files = $event.srcElement.files;
if (this.isValidCSVFile(files[0])) {
const input = $event.target;
const reader = new FileReader();
reader.readAsText(input.files[0]);
console.log('after read as text');
reader.onload = (e) => {
console.log('onload');
const csvData = reader.result;
const temp = ( csvData as string).replace(/\r/g, '\n');
const csvRecordsArray = ( temp as string).split(/\r\n|\n/);
const headersRow = this.getHeaderArray(csvRecordsArray);
this.records = this.getDataRecordsArrayFromCSVFile(csvRecordsArray, headersRow.length);
(document.getElementById('sendButton') as HTMLInputElement).disabled = false;
};
} else {
alert('Please import valid .csv file.');
this.fileReset();
}
}
getDataRecordsArrayFromCSVFile(csvRecordsArray: any, headerLength: any) {
console.log('getDataRecordsArrayFromCSVFile');
const csvArr = [];
for (let i = 1; i < csvRecordsArray.length; i++) {
const curruntRecord = (csvRecordsArray[i] as string).split(',');
if (curruntRecord.length === headerLength) {
const csvRecord: CSVRecord = new CSVRecord();
csvRecord.code = curruntRecord[0].trim();
csvRecord.date = new Date(curruntRecord[1].trim());
csvRecord.value = Number(curruntRecord[2].trim());
csvRecord.period = curruntRecord[3].trim();
csvArr.push(csvRecord);
}
}
return csvArr;
}
isValidCSVFile(file: any) {
return file.name.endsWith('.csv');
}
getHeaderArray(csvRecordsArr: any) {
console.log('getHeaderArray');
const headers = (csvRecordsArr[0] as string).split(',');
const headerArray = [];
for (const header of headers){
headerArray.push(header);
}
return headerArray;
}
fileReset() {
this.csvReader.nativeElement.value = '';
this.records = [];
}
This is the function ehich dend the data to the server:
sendCSV(){
console.log('click');
const url = this.apiService.baseUrl + 'API/SeriesAPI/UploadSeriesData?option=1';
// const body = JSON.stringify(this.records);
this.http.post(url, this.records ,
{
headers: new HttpHeaders({
'Content-Type': 'application/json;chrset=UTF-8'
})
}
)
.subscribe(x =>
{
console.log(x);
});
}
Debugger chrome

Related

How To Save API DATA Into MYSQL Database

how can i convert this working mongoose code to a working MYSQL code?, i have a project where i fetch data from online api that updates every 24hours auto, and i need to insert that data information to database mysql but im new to mysql. im using react and node for my project.
import fetch from 'node-fetch';
import mongoose, { mongo } from 'mongoose';
mongoose.connect("mongodb://127.0.0.1:27017/highscore");
const postSchema = new mongoose.Schema({
position: {
type: Number,
required: true
},
id: {
type: Number,
required: true
},
score: {
type: Number,
required: true
},
});
const Post = mongoose.model('Players', postSchema);
async function getPosts() {
const getPlayers = await fetch("http://localhost:3008/api/highscore/players");
const response = await getPlayers.json();
for( let i = 0;i < response.players.length; i++){
const post = new Post({
position: response.players[i]['position'],
id: response.players[i]['id'],
score: response.players[i]['score'],
});
post.save();
}
}
getPosts();
SOME backend code i put together but have no idea where to add the api
app.post('/create', (req, res) => {
const position = req.body.position
const name = req.body.name
const alliance = req.body.alliance
const points = req.body.points
db.query("INSERT INTO stats (position, name, alliance, points) VALUES (?,?,?,?)",
[position, name, alliance, points],
(err, result) => {
if (err) {
console.log(err)
} else {
res.send("Values Inserted")
}
}
);
});
*** COMPLETE CODE THAT FETCHES DATA FROM API ***
const Table = () => {
const [playerName, setPlayerName] = useState([]);
const [playerRank, setPlayerRank] = useState([]);
const [player, setPlayer] = useState([]);
const [perPage, setPerPage] = useState(10);
const [size, setSize] = useState(perPage);
const [current, setCurrent] = useState(1);
const [players, setPlayers] = useState();
const fetchData = () => {
const playerAPI = 'http://localhost:3008/api/players';
const playerRank = 'http://localhost:3008/api/highscore/players';
const getINFOPlayer = axios.get(playerAPI)
const getPlayerRank = axios.get(playerRank)
axios.all([getINFOPlayer, getPlayerRank]).then(
axios.spread((...allData) => {
const allDataPlayer = allData[0].data.players
const getINFOPlayerRank = allData[1].data.players
const newPlayer = allDataPlayer.map(name => {
const pr = getINFOPlayerRank.find(rank => name.id === rank.id)
return {
id: name.id,
name: name.name,
status: name.status,
alliance: name.alliance,
position: pr?.position,
score: pr?.score
}
})
setPlayerName(allDataPlayer)
setPlayerRank(getINFOPlayerRank)
console.log(getINFOPlayerRank)
console.log(newPlayer)
setPlayer(newPlayer)
})
)
}
useEffect(() => {
fetchData()
}, [])

Zoom camera inside room and show interior of the room

We are using forge viewer in our web application. We need to zoom camera inside room and show interior of the room.
Please help me to find out that how we can view room interior in forge viewer.
This is a duplicate question on SO, here is an already answered link: https://stackoverflow.com/a/65827867/5747150
You may check out this sample. It’s a revision of my sample forge-viewer-traveling-path. It will move the viewer camera smoothly to the center point of the room’s bounding box.
Demo: https://youtu.be/3MzihDJpi70
Here is the main extension: https://github.com/yiskang/forge-viewer-traveling-path/blob/room-navigation/public/js/MoveToRoomExt.js
/////////////////////////////////////////////////////////////////////
// Copyright (c) Autodesk, Inc. All rights reserved
// Written by Forge Partner Development
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
/////////////////////////////////////////////////////////////////////
(function () {
class RoomListPanel extends Autodesk.Viewing.UI.DockingPanel {
constructor(parent) {
const options = {};
// Height adjustment for scroll container, offset to height of the title bar and footer by default.
if (!options.heightAdjustment)
options.heightAdjustment = 70;
if (!options.marginTop)
options.marginTop = 0;
//options.addFooter = false;
const viewer = parent.viewer;
super(viewer.container, viewer.container.id + 'RoomListPanel', 'Rooms', options);
this.container.classList.add('adn-docking-panel');
this.container.classList.add('adn-room-list-panel');
this.createScrollContainer(options);
this.viewer = viewer;
this.parent = parent;
this.options = options;
this.uiCreated = false;
this.addVisibilityListener(async (show) => {
if (!show) return;
if (!this.uiCreated)
await this.createUI();
});
}
async createUI() {
this.uiCreated = true;
const div = document.createElement('div');
const treeDiv = document.createElement('div');
div.appendChild(treeDiv);
this.treeContainer = treeDiv;
this.scrollContainer.appendChild(div);
const data = await this.getRoomData();
this.buildTree(data);
}
async getRoomData() {
const getRoomDbIds = () => {
return new Promise((resolve, reject) => {
this.viewer.search(
'Revit Rooms',
(dbIds) => resolve(dbIds),
(error) => reject(error),
['Category'],
{ searchHidden: true }
);
});
};
const getPropertiesAsync = (dbId) => {
return new Promise((resolve, reject) => {
this.viewer.getProperties(
dbId,
(result) => resolve(result),
(error) => reject(error),
);
});
}
const data = [];
try {
const roomDbIds = await getRoomDbIds();
if (!roomDbIds || roomDbIds.length <= 0) {
throw new Error('No Rooms found in current model');
}
for (let i = 0; i < roomDbIds.length; i++) {
const dbId = roomDbIds[i];
const propData = await getPropertiesAsync(dbId);
data.push({
id: propData.externalId,
dbId,
name: propData.name
});
}
} catch (ex) {
console.warn(`[RoomListPanel]: ${ex}`);
throw new Error('Failed to extract room data');
}
return data;
}
getBoundingBox(dbId) {
const model = this.viewer.model;
const it = model.getInstanceTree();
const fragList = model.getFragmentList();
let bounds = new THREE.Box3();
it.enumNodeFragments(dbId, (fragId) => {
let box = new THREE.Box3();
fragList.getWorldBounds(fragId, box);
bounds.union(box);
}, true);
return bounds;
}
buildTree(data) {
const nodes = [];
for (let i = 0; i < data.length; i++) {
const node = {
id: data[i].id,
dbId: data[i].dbId,
type: 'spaces',
text: data[i].name
};
nodes.push(node);
}
console.log(nodes);
$(this.treeContainer)
.jstree({
core: {
data: nodes,
multiple: false,
themes: {
icons: false,
name: 'default-dark'
}
},
sort: function (a, b) {
const a1 = this.get_node(a);
const b1 = this.get_node(b);
return (a1.text > b1.text) ? 1 : -1;
},
checkbox: {
keep_selected_style: false,
three_state: false,
deselect_all: true,
cascade: 'none'
},
types: {
spaces: {}
},
plugins: ['types', 'sort', 'wholerow'],
})
.on('changed.jstree', async (e, data) => {
console.log(e, data);
console.log(data.node.original);
const { dbId } = data.node.original;
if (!dbId) return;
const bbox = this.getBoundingBox(dbId);
const center = bbox.center();
const point = new THREE.Vector3(center.x, center.y, bbox.min.z);
this.parent.tweenToPoint(point);
});
}
}
class MoveToRoomExtension extends Autodesk.Viewing.Extension {
constructor(viewer, options) {
super(viewer, options);
this.cameraTweenTool = null;
this.uiCreated = false;
}
onToolbarCreated(toolbar) {
const panel = new RoomListPanel(this);
viewer.addPanel(panel);
this.panel = panel;
const roomsPanelButton = new Autodesk.Viewing.UI.Button('room-panel-button');
roomsPanelButton.onClick = () => {
panel.setVisible(!panel.isVisible());
};
roomsPanelButton.setToolTip('Open room list panel');
this.group = new Autodesk.Viewing.UI.ControlGroup('room-nav-tool-group');
this.group.addControl(roomsPanelButton);
toolbar.addControl(this.group);
}
tweenToPoint(point) {
this.viewer.setActiveNavigationTool('bimwalk');
const views = [];
const up = new THREE.Vector3(0, 0, 1);
const currentEye = this.viewer.navigation.getPosition().clone();
const targetPos = point.clone().add(up.clone().multiplyScalar(1.7 * 3.2808399));
const sightDir = point.clone().sub(currentEye).normalize();
const eyeLen = this.viewer.navigation.getEyeVector().length();
const target = targetPos.clone().add(sightDir.clone().multiplyScalar(eyeLen));
views.push({
up: up.toArray(),
eye: targetPos.toArray(),
target: target.toArray()
});
this.processTweens(views);
}
executeTweenPromised(view) {
return new Promise((resolve, reject) => {
const onTweenExecuted = (event) => {
console.log(event);
this.viewer.removeEventListener(
Autodesk.ADN.CameraTweenTool.CAMERA_TWEEN_ANIMATION_COMPLETED_EVENT,
onTweenExecuted
);
resolve();
};
this.viewer.addEventListener(
Autodesk.ADN.CameraTweenTool.CAMERA_TWEEN_ANIMATION_COMPLETED_EVENT,
onTweenExecuted
);
this.cameraTweenTool.tweenCameraTo({ viewport: view });
});
}
processTweens(data) {
//process each promise
//refer to http://jsfiddle.net/jfriend00/h3zaw8u8/
const promisesInSequence = (tasks, callback) => {
const results = [];
return tasks.reduce((p, item) => {
return p.then(() => {
return callback(item).then((data) => {
results.push(data);
return results;
});
});
}, Promise.resolve());
};
//start to process
return promisesInSequence(data, (d) => this.executeTweenPromised(d));
}
async load() {
const loadCSS = (href) => new Promise(function (resolve, reject) {
const el = document.createElement('link');
el.rel = 'stylesheet';
el.href = href;
el.onload = resolve;
el.onerror = reject;
document.head.appendChild(el);
});
await Promise.all([
Autodesk.Viewing.Private.theResourceLoader.loadScript('https://unpkg.com/#tweenjs/tween.js#18.6.4/dist/tween.umd.js', 'TWEEN'),
Autodesk.Viewing.Private.theResourceLoader.loadScript('https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js', '$'),
Autodesk.Viewing.Private.theResourceLoader.loadScript('https://cdnjs.cloudflare.com/ajax/libs/jstree/3.3.7/jstree.min.js', '$'),
loadCSS('https://cdnjs.cloudflare.com/ajax/libs/jstree/3.3.7/themes/default/style.min.css'),
loadCSS('https://cdnjs.cloudflare.com/ajax/libs/jstree/3.3.7/themes/default-dark/style.min.css'),
this.viewer.loadExtension('Autodesk.BimWalk'),
this.viewer.loadExtension('Autodesk.ADN.CameraTweenTool')
]);
this.viewer.setBimWalkToolPopup(false);
this.cameraTweenTool = this.viewer.getExtension('Autodesk.ADN.CameraTweenTool');
console.log('MoveToRoomExtension has been loaded.');
return true;
}
async unload() {
this.viewer.unloadExtension('Autodesk.ADN.CameraTweenTool');
this.viewer.setBimWalkToolPopup(true);
delete this.cameraTweenTool;
this.cameraTweenTool = null;
console.log('MoveToRoomExtension has been unloaded.');
return true;
}
}
Autodesk.Viewing.theExtensionManager.registerExtension('Autodesk.ADN.MoveToRoomExtension', MoveToRoomExtension);
})();

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string or an instance of Buffer or URL

I am trying to control some devices remotely by getting sensor data: Temperature, Humidity, etc..
I don't know why but in the code there is something that is not working perfectly. I struggle reading and re-reading the code but still .. I could not figure our the origin of the error:
node:internal/errors:464
ErrorCaptureStackTrace(err);
^
TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string or an instance of Buffer or URL. Received undefined
at Object.openSync (node:fs:577:10)
at Object.readFileSync (node:fs:453:35)
at readTd (C:\Users\Mehdi\Desktop\WS2022\IoT_Mehdi\iotrlws2122cons2-ge37vok\6_averageSensors.js:175:24)
at C:\Users\Mehdi\Desktop\WS2022\IoT_Mehdi\iotrlws2122cons2-ge37vok\6_averageSensors.js:201:46
at step (C:\Users\Mehdi\Desktop\WS2022\IoT_Mehdi\iotrlws2122cons2-ge37vok\6_averageSensors.js:33:23)
at Object.next (C:\Users\Mehdi\Desktop\WS2022\IoT_Mehdi\iotrlws2122cons2-ge37vok\6_averageSensors.js:14:53)
at fulfilled (C:\Users\Mehdi\Desktop\WS2022\IoT_Mehdi\iotrlws2122cons2-ge37vok\6_averageSensors.js:5:58)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
code: 'ERR_INVALID_ARG_TYPE'
}
import { Logger, createLogMessage } from './utils/Logger';
import { AffordanceType, RecipientType, Operation } from './utils/LogTemplate';
import { HttpsClientFactory } from "#node-wot/binding-http";
import ConsumedThing from "#node-wot/core/dist/consumed-thing";
import { Servient } from "#node-wot/core";
import fs = require("fs");
import path = require("path");
import { exit } from "process";
import { ThingDescription } from "wot-typescript-definitions";
const servient = new Servient();
let creds = {
"urn:dev:ops:32473-sensehat-001": {
// Here the username and password I Provided you with
"username": "xxxxxx",
"password": "xxxxxx"
},
"urn:dev:ops:32473-sensehat-002": {
// Here the username and password I Provided you with
"username": "xxxxxx",
"password": "xxxxxx"
},
"urn:dev:ops:32473-sensehat-003": {
// Here the username and password I Provided you with
"username": "xxxxxx",
"password": "xxxxxx"
},
"urn:dev:ops:32473-sensehat-004": {
// Here the username and password I Provided you with
"username": "xxxxxx",
"password": "xxxxxx"
},
"urn:dev:ops:32473-HueIndoorSensor-1": {
// Here the username and password I Provided you with
"username": "xxxxxx",
"password": "xxxxxx"
},
"urn:dev:ops:32473-HueIndoorSensor-2": {
// Here the username and password I Provided you with
"username": "xxxxxx",
"password": "xxxxxx"
},
"urn:dev:ops:32473-HueOutdoorSensor-1": {
// Here the username and password I Provided you with
"username": "xxxxxx",
"password": "xxxxxx"
},
};
servient.addClientFactory(new HttpsClientFactory(null));
servient.addCredentials(creds);
const delay = async (ms: number) => {
await new Promise<void>(resolve => setTimeout(() => resolve(), ms));
}
var logger = new Logger();
async function readLoggedProperty(thing: any, propertyName: string, options?: any): Promise<any> {
var logMsg = createLogMessage(
{ name: propertyName, type: AffordanceType.Property },
1,
Operation.Readproperty,
RecipientType.Thing,
thing.getThingDescription().title,
thing.getThingDescription().id,
null
);
logger.addMessage(logMsg);
// logger.saveMessages("6_averageSensors", "HTTP");
let ret = await thing.readProperty(propertyName, options);
var logMsg = createLogMessage(
{ name: propertyName, type: AffordanceType.Property },
1,
Operation.Invokeaction,
RecipientType.Controller,
thing.getThingDescription().title,
thing.getThingDescription().id,
ret
);
logger.addMessage(logMsg);
// logger.saveMessages("6_averageSensors", "HTTP");
return ret;
}
async function invokeLoggedAction(thing: any, actionName: string, params?: any, options?: any): Promise<any> {
var logMsg = createLogMessage(
{ name: actionName, type: AffordanceType.Action },
1,
Operation.Invokeaction,
RecipientType.Thing,
thing.getThingDescription().title,
thing.getThingDescription().id,
params
);
logger.addMessage(logMsg);
// logger.saveMessages("6_averageSensors", "HTTP");
await thing.invokeAction(actionName, params, options).then(function (ret) {
var logMsg = createLogMessage(
{ name: actionName, type: AffordanceType.Action },
1,
Operation.Invokeaction,
RecipientType.Controller,
thing.getThingDescription().title,
thing.getThingDescription().id,
ret
);
logger.addMessage(logMsg);
logger.saveMessages("6_averageSensors", "HTTP");
return ret;
})
}
let td_sensHats1: ThingDescription;
function readTd (tdPath: string){
let read_file = fs.readFileSync(tdPath);
var td = JSON.parse(read_file.toString());
return td;
}
var ConsumedthingsHat=[]
var ConsumedthingsHue=[]
async function main() {
var array_SenseHat = ["SenseHat1.json","SenseHat2.json","SenseHat3.json","SenseHat4.json"]; //declaration
var array_Hue=["Hue Indoor Sensor 1.json","Hue Indoor Sensor 2.json","Hue Outdoor Sensor.json"]; //declaration
await servient.start().then(async (WoT) => {
for (let m = 0 ; m < 5; m ++)
{
var td = readTd(array_SenseHat[m]);
const thing = await WoT.consume(td) as ConsumedThing;
console.log(thing)
ConsumedthingsHat.push(thing);
}
for (let m = 0 ; m < 4; m ++)
{
var td = readTd(array_Hue[m]);
const thing = await WoT.consume(td) as ConsumedThing;
console.log(thing)
ConsumedthingsHue.push(thing);
}
// await servient.start().then(async (WoT) => {
const thing1 = await WoT.consume(ConsumedthingsHat[0]);
// Average Teamperature
let array_tempvalues: number[] = [];
for (let j = 0; j < 5; j++) {
// var td = await readTd(array_SenseHat[j]);
// const temp_Value = await WoT.consume(td) as ConsumedThing;
let temp = await readLoggedProperty(ConsumedthingsHat[j], "temperature");
await array_tempvalues.push(temp);
}
let avgTemp = array_tempvalues.reduce((total, actual_TempValue, index, array) => {
return (total + actual_TempValue) / array.length;
})
let payload1 = { "avgTmp": avgTemp.toFixed(2) };
await invokeLoggedAction(thing1, "showMessage", payload1);
// Avg pressure on hat2
const thing2 = await WoT.consume(ConsumedthingsHat[1]);
let arrayPressureValues: number[] = [];
for (let j = 0; j < 5; j++) {
// const element = await WoT.consume(ConsumedthingsHat[j]);
let pressure = await readLoggedProperty(ConsumedthingsHat[j], "pressure");
arrayPressureValues.push(pressure);
}
let avgPress = arrayPressureValues.reduce((total, actual_Pressure, ind, array) => {
return (total + actual_Pressure) / array.length;
})
let payload2 = { "avgPressure": avgPress.toFixed(2) };
await invokeLoggedAction(thing2, "showMessage", payload2);
// Avg humidity on hat2
let arrayHumidity: number[] = [];
const thing3 = await WoT.consume(ConsumedthingsHat[2]);
for (let j = 0; j <5; j++) {
// const element = await WoT.consume(ConsumedthingsHat[j]);
let humid = await readLoggedProperty(ConsumedthingsHat[j], "humidity");
arrayHumidity.push(humid);
}
let avgHumid = arrayHumidity.reduce((total, actual_Humidity, ind, array) => {
return (total + actual_Humidity) / array.length;
})
let payload3 = { "textString": avgHumid.toFixed(2) };
await invokeLoggedAction(thing3, "showMessage", payload3);
// Avg humidity on hat2
let arrayLight: number[] = [];
const thing4 = await WoT.consume(ConsumedthingsHue[0]);
for (let j = 0; j < 5; j++) {
// const element = await WoT.consume(ConsumedthingsHue[j]);
let info = await readLoggedProperty(ConsumedthingsHat[j], "lightInformation");
arrayLight.push(info["state"]["lightlevel"]);
}
let avgLight = arrayLight.reduce((total, actual_Light, ind, array) => {
return (total + actual_Light) / array.length;
})
let payload4 = { "textString": avgLight.toFixed(2) };
await invokeLoggedAction(thing4, "showMessage", payload4);
await delay(5000).then(async () => {
for (let j = 0; j < 5; j++) {
const element1= array_SenseHat[j];
await invokeLoggedAction(element1,"clear");
console.log("Nothing Displayed");
}
})
})
}
main()
Looking forward for help

Unable to show blob url in "pdf-viewer" => "ng2-pdf-viewer" in Angular 10

I have an API which is returning uploaded file as blob. When I try to bind src with blob URL then it does not show anything, however, when I try to bind direct URL then it can show PDF file. Here is my code given below.
My TS code
downloadFile(fileData: Fileuploader) {
this.tempBlob= null;
//Fetching Data File
this.apiservice.getDownloadfile(fileData).subscribe(
(retFileData: any) => {
this.tempRetFileData = retFileData;
this.tempBlob = new Blob([retFileData], { type: this.contentType });
},
(err: Error) => {
},
() => {
const blob: Blob = new Blob([this.tempBlob], { type: this.contentType });
const fileName: string ='ilvsna.pdf';
this.myBlobURL = URL.createObjectURL(blob);
}
);
}
HTML
<pdf-viewer [src]="myBlobURL"
[render-text]="true"
[original-size]="false"
style="width: 400px; height: 500px"
></pdf-viewer>
Note: if I set myBlobURL URL to 'https://vadimdez.github.io/ng2-pdf-viewer/assets/pdf-test.pdf' then it can display
I think I have a solution for you. You can use ArrayBuffer. #N.F. Code is correct, however, you said that you got error in the line => this.pdfSrc = new Uint8Array(fileReader.result);
So, change the line into => this.pdfSrc = new Uint8Array(fileReader.result as ArrayBuffer);.Finally, your ts code should look like below=>
downloadFile(fileData: Fileuploader) {
this.tempBlob= null;
//Fetching Data File
this.apiservice.getDownloadfile(fileData).subscribe(
(retFileData: any) => {
this.tempRetFileData = retFileData;
this.tempBlob = new Blob([retFileData], { type: this.contentType });
const fileReader = new FileReader();
fileReader.onload = () => {
this.pdfSrc = new Uint8Array(fileReader.result as ArrayBuffer);
};
fileReader.readAsArrayBuffer(this.tempBlob);
},
(err: Error) => {
}
);
}
Try this.
ts
pdfSrc: Uint8Array;
downloadFile(fileData: Fileuploader) {
this.tempBlob= null;
//Fetching Data File
this.apiservice.getDownloadfile(fileData).subscribe(
(retFileData: any) => {
this.tempRetFileData = retFileData;
this.tempBlob = new Blob([retFileData], { type: this.contentType });
const fileReader = new FileReader();
fileReader.onload = () => {
this.pdfSrc = new Uint8Array(fileReader.result as ArrayBuffer);
};
fileReader.readAsArrayBuffer(this.tempBlob);
},
(err: Error) => {
}
);
}
html
<pdf-viewer [src]="pdfSrc"
[render-text]="true"
[original-size]="false"
style="width: 400px; height: 500px"
></pdf-viewer>
I resolve with window.URL.createObjectURL of my return blob file from service:
-- ts file
this.obuService.getObuDocument(obuId, fileId).subscribe(
(data: HttpResponse<Blob>) => {
const url = window.URL.createObjectURL(data.body);
this.src = url;
this.viewPDF = true;
}
);
-- service
getObuDocument(obuId: number, fileId: number): Observable<any> {
const options = {
observe: 'response' as 'body',
Accept: 'application/pdf',
responseType: 'blob' as 'blob'
};
return this.http.get(this.apiUrl + '/' + obuId + '/upload/' + fileId, options)
.pipe(catchError(err => { throw err; }));
}

VueJs Axios Post FormData Parameters

We are using Vue in our frontend application, and for one of our REST service our backend server(using spring and java) expects to have the below data structure:
public class MAProductsUploadRequest
{
public List<MAProductUploadRequest> products;
}
public class MAProductUploadRequest {
public String productName;
public String productDescription;
public double productPrice;
public int productOrder;
public MultipartFile productImage=null;
public double cropX;
public double cropY;
public double cropWidth;
public double cropHeight;
public int categoryId;
}
And in our Vuejs application we tried to post the data as in the below code:
addProducts: function () {
console.log("Add Products Working. Total Product Count:"+this.excelProducts.length);
let header = {
headers: auth.getAuthHeader()
};
let formData = new FormData();
for (let i=0;i<this.excelProducts.length;i++ ) {
console.log("Starting loop:"+i);
var prod = this.excelProducts[i];
console.log("Product Before:"+prod);
if (document.getElementById('photo-image-'+i) !== null) {
if(document.getElementById('photo-image-'+i).files.length !== 0) {
console.log("Getting Image For Prod");
prod.productImage = document.getElementById('photo-image-'+i).files[0] ;
}
}
prod.cropX = this.cropProp.x;
prod.cropY = this.cropProp.y;
prod.cropWidth = this.cropProp.width;
prod.cropHeight = this.cropProp.height;
prod.rotate = this.cropProp.rotate;
console.log("Product After:"+prod);
formData.append("products[]",prod);
}
for (var pair of formData.entries()) {
console.log(pair[0]+ ', ' + pair[1]);
}
//console.log("Form Data:"+formData.products);
if (formData.products !== null) {
axios.post(`${API_URL}/company/uploadProducts`, formData, header).then((response) => {
logForDevelopment(response);
this.getProducts();
this.product = {
id: '',
name: '',
description: '',
price: '',
photo: '',
isEdit: false
};
this.excelProducts = [];
this.isPhotoChosen = false;
this.isPhotosChosen = [];
this.cropImg = '';
document.getElementById('photo-image').value = null;
this.isLoading = false;
}).catch((error) => {
this.isLoading = false;
if(error.response) {
logForDevelopment(error);
document.getElementById('photo-image').value = null;
if(error.response.status === 401 || error.response.status === 403) {
auth.afterInvalidToken('login');
}
}
})
} else {
console.log("Form Data Is Empty");
}
},
But when we use this code (even if the photo-image was null) the backend server returns HTTP 500 error. Because the products array seems null.
I wasn't able to figure it out where the problem may be in the Vuejs code?
EDIT: (I'VE also tried the below code but the still same result)
addProducts: function () {
console.log("Add Products Working. Total Product Count:"+this.excelProducts.length);
let header = {
headers: auth.getAuthHeader()
};
let formData = new FormData();
let prods = [];
for (let i=0;i<this.excelProducts.length;i++ ) {
console.log("Starting loop:"+i);
let prod = this.excelProducts[i];
let subFormData = new FormData();
subFormData.append("productName",prod.productName);
subFormData.append("productDescription",prod.productDescription);
subFormData.append("productPrice",prod.price);
subFormData.append("categoryId",prod.categoryId);
subFormData.append("cropX",this.cropProp.x);
subFormData.append("cropY",this.cropProp.y);
subFormData.append("cropWidth",this.cropProp.width);
subFormData.append("cropHeight",this.cropProp.height);
prods.push(subFormData);
if (document.getElementById('photo-image-'+i) !== null) {
if(document.getElementById('photo-image-'+i).files.length !== 0) {
console.log("Getting Image For Prod");
subFormData.productImage = document.getElementById('photo-image-'+i).files[0] ;
}
}
}
formData.append("products",prods);
console.log("Form Data:"+formData);
if (formData.products !== null) {
axios.post(`${API_URL}/company/uploadProducts`, formData, header).then((response) => {
logForDevelopment(response);
this.getProducts();
this.product = {
id: '',
name: '',
description: '',
price: '',
photo: '',
isEdit: false
};
this.excelProducts = [];
this.isPhotoChosen = false;
this.isPhotosChosen = [];
this.cropImg = '';
document.getElementById('photo-image').value = null;
this.isLoading = false;
}).catch((error) => {
this.isLoading = false;
if(error.response) {
logForDevelopment(error);
//document.getElementById('photo-image').value = null;
if(error.response.status === 401 || error.response.status === 403) {
auth.afterInvalidToken('login');
}
}
})
} else {
console.log("Form Data Is Empty");
}
},
What I'm actually trying to achive is, our below code works fine when sending single product info to our backend service, but I want to make it an array so send multiple products at once:
addProduct: function () {
let header = {
headers: auth.getAuthHeader()
};
let formData = new FormData();
formData.append('productName', this.product.name);
formData.append('productDescription', this.product.description === '' ? "" : this.product.description);
formData.append('productPrice', this.product.price);
formData.append('categoryId', this.product.categoryId);
if(document.getElementById('photo-image').files.length !== 0) {
formData.append('productImage', document.getElementById('photo-image').files[0]);
}
formData.append('cropX', this.cropProp.x);
formData.append('cropY', this.cropProp.y);
formData.append('cropWidth', this.cropProp.width);
formData.append('cropHeight', this.cropProp.height);
formData.append('rotate', this.cropProp.rotate);
console.log(formData);
axios.post(`${API_URL}/company/products`, formData, header).then((response) => {
logForDevelopment(response);
this.getProducts();
this.product = {
id: '',
name: '',
description: '',
price: '',
photo: '',
isEdit: false
};
this.isPhotoChosen = false;
this.cropImg = '';
document.getElementById('photo-image').value = null;
this.isLoading = false;
}).catch((error) => {
this.isLoading = false;
if(error.response) {
logForDevelopment(error);
document.getElementById('photo-image').value = null;
if(error.response.status === 401 || error.response.status === 403) {
auth.afterInvalidToken('login');
}
}
})
},
Does anyone have any idea about that?
You can also look at the screenshot of my application in below(I want to send all the items in screenshot , at once )
Your issue is probably il the formData.append("products[]",prod) method of your FormData class, try changing formData.append("products[]",prod) with formData.products.push(prod).
Furthermore in your axios call the payload should be formData.products if you API endpoint expects the products right?
Try axios.post(${API_URL}/company/uploadProducts, formData.products, header).
I do not see any syntax issue relative to Vue, hope this helps. (And of course check what is sent by XHR in devtools as suggested in the comments)