problem is "request react native form-data" - react-native

i have some problem request video, image to server,
about 3MB video, 10kb image * 2
it's long time
about 30~40s
but, when quick case, just 4s
i don't know what happen.
how i reduce form data body
body.append("profilePhoto", "profilePhoto");
body.append("profileVideo", "profileVideo");
body.append("thumbnailPhoto", "thumbnailPhoto");
body.append("profileMessage", profileMessage);
body.append("userIdentifier", userIdentifier);
body.append("firebaseToken", nickname);
body.append("nickname", nickname);
body.append("dob", dob);
body.append("bodyType", bodyType);
body.append("sexType", sexType);
body.append("lat", lat);
body.append("lng", lng);
body.append("loginType", loginType);
const { data: signUpResult } = await client.post("/signup", body, {
headers: { "content-type": "multipart/form-data" },
});

Related

VUE.js Refreshing img scr after submitting a form

I'm facing the following issue with vue.js2.
After submitting a form, I want to refresh image src.
When the form is submitted, a new image with a chart is generated in the back-end.
This new chart image replaces the old one, however, the URL stays the same.
To update image, I'm using v-bind on image src and bind it to one of the data variables.
The starting image which is displayed before submitting the form is placeholder.jpg.
After receiving a response, I call changeChart method to update it with graph.jpg.
This action works and image is updated
The problem I'm facing here is when I update one of the values and click submit again, the image does not change.
However, when I click clear method first and set chart_url to placeholder.jpg again on next submit, image changes properly.
<v-img
v-bind:src=this.chart_url
</v-img>
<script>
export default {
name: "CenterComponent",
data: function () {
return {
value1: "",
value2: "",
value3: "",
output: null,
chart_url: "http://127.0.0.1:5000/media/pictures/placeholder.jpg",
}
},
methods:{
clear(){
this.value1 = "";
this.value2 = "";
this.value3 = "";
this.output = "";
this.chart_url = "http://127.0.0.1:5000/media/pictures/placeholder.jpg";
},
changeChart(){
this.chart_url = "http://127.0.0.1:5000/media/pictures/graph.jpg"
},
submitForm(){
fetch("http://127.0.0.1:5000/predict",{
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
value1: this.value1,
value2: this.value2,
value3: this.value3
})
}
).then(response => {
if (response.ok) {
return response.json();
}
}).then(data => {
this.output = data["prediction"];
this.changeChart();
});
}
},
};
</script>
As you say, the first time you're submitting the form you actually change the url from 'placeholder.jpg' to 'graph.jpg', and on subsequent submits it remains as 'graph.jpg'.
This means that the browser is not going to fetch that image again every time it changes to 'graph.jpg' as it is cached. To make the browser fetch a new image you can try cache-busting by appending a random number to the end of the url in your changeChart method. You're effectively telling the browser that it doesn't have this image, so go fetch it.
changeChart(){
const randomNumber = Math.floor(Math.random() * 1000)
this.chart_url = `http://127.0.0.1:5000/media/pictures/graph.jpg?cachebust=${randomNumber}`
},
This will append a random number between 1-1000, but you could obviously improve this depending on your use case.
Alternatively, create a unique image name on the server when it is processed, and return this new name in the response of the POST call. That way you won't have this issue to start with.

Error Ajxa call in asp.net xhr.send( options.hasContent && options.data || null )

I tried to so hard to solve it but couldn't.
I got error
xhr.send( options.hasContent && options.data || null )
while saving data this error shows in Jquery.js.
Code is working perfectly in debug mode in vs 2022. I can save data in debug mode. But when
I compile (Publish) this project. I hosted in IIS and every things working perfectly but not in this form When I try to post data then I got same error.
I tried to send header but not working..
var token =
$('input:hidden[name="__RequestVerificationToken"]').val();
headers: { RequestVerificationToken: token },
var detailsList = new Array();
var detailsObj = new Object();
$("#tblDropItem tbody tr").each(function () {
let row = $(this);
let itemId = Number(row.find('.item_detl').attr('purItem_id'));
detailsObj = {
ItemId: itemId,
ItemName: row.find(".item_detl").val(),
Quantity: parseFloat(row.find(".quantity_detl").val()),
UnitId: Number(row.find('.unit_detl').attr('unit_id')),
Rate: parseFloat(row.find(".rate_detl").val()),
Amount: parseFloat(row.find(".amount_detl").val()),
}
if (detailsObj.ItemName) {
detailsList.push(detailsObj);
}
});
var postData = {
PurMode: $("#PurMode").val(),
PurDate: $("#PurDate").val(),
SupId: $("#SupId option:selected").val(),
SubAmount: parseFloat($("#SubAmount").val()),
Discount: parseFloat($("#DiscountPercent").val()),
DiscountAmount: parseFloat($("#Discount").val()),
TotalAmount: parseFloat($("#TotalAmount").val()),
Remarks: $("#Remarks").val(),
Taxable: parseFloat($("#Taxable").val()),
VatAmount: parseFloat($("#VatAmount").val()),
VATable: parseFloat($("#VATable option:selected").val())
PurchaseDetailItemList: detailsList,
__RequestVerificationToken: $("input[name=__RequestVerificationToken]").val(),
}
$.ajax({
type: "POST",
url: "/Purchase/SavePurchase",
dataType: 'JSON',
data: postData,
async:false,
success: function (result) {
toastr.success('Data Saved Successfully');
window.location = "#Url.Content("~/Purchase/Index")";
},
error: function (result) {
toastr.error("Cann't Save Data.");
}
});
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult SavePurchase(PurchaseDTO model)
{
if (!ModelState.IsValid)
{
return Json("error");
}
//code...
}
Can you please suggest any mistake..
Everything is correct, maybe you have hosted incorrectly in iis, make sure your post url is valid in console.

Creating a Heatmap for Rooms - No Structureinfo

I'm working on a project in which I have to generate a heatmap for some sensors that are beeing rendered inside of a modell using forgeviewer. For the implementation I'm following this tutorial: https://forge.autodesk.com/en/docs/dataviz/v1/developers_guide/examples/create_heatmap_for_rooms/
The modell I'm using was generated through Revit and translated into .svf using the Model-Derivative-API.
My problem now is, that I cant get any room or level data from my model which are needed for the generation of the heatmap.
These lines always give me no rooms or levels, eventhough there are rooms shown in the viewers modellbrowser as shown in the picture below.
modellbrowser with rooms
const structureInfo = new Autodesk.DataVisualization.Core.ModelStructureInfo(viewer.model);
console.log("STRUCTUREINFO");
console.log(structureInfo);
...
const shadingdata= await structureInfo.generateSurfaceShadingData(devices);
console.log("SHADINGDATA");
console.log(shadingdata);
StructureInfo in console
ShadingData in console
Question now is: Why cant I get any room or level data and how can I fix this?
The only thing that came to my mind so far that I have tried was to convert the revit file into .nwd using navisworks and translating that file into .svf. But the results where the same.
Here is some more Code. Please note that the application is clientside only and wont go into production like this. I'm only creating a prototype for presentations.
export const initializeViewer = async (urn: string) => {
let viewer: Autodesk.Viewing.GuiViewer3D;
fetch("https://developer.api.autodesk.com/authentication/v1/authenticate", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams({
client_id: "ClinetID",
client_secret: "ClentSecret",
grant_type: "client_credentials",
scope: "viewables:read",
}),
}) .then((res) => res.json())
.then((value) => {
const options = {
document: urn,
env: "AutodeskProduction",
accessToken: value.access_token,
api: "derivativeV2",
};
var container = document.getElementById("viewer-container");
if (container !== null) {
viewer = new Autodesk.Viewing.GuiViewer3D(container, {
extensions: [],
});
}
Autodesk.Viewing.Initializer(options, function onInitialized() {
addEvents();
viewer.start();
Autodesk.Viewing.Document.load(urn, onSuccess, onFailure);
});
});
const addEvents = () => {
viewer.addEventListener(Autodesk.Viewing.GEOMETRY_LOADED_EVENT, () => {
loadExtensions();
onModelLoaded(viewer);
});
....
....
async function onModelLoaded(viewer: Autodesk.Viewing.GuiViewer3D) {
const dataVizExtn: any | Autodesk.Extensions.DataVisualization = await viewer.loadExtension("Autodesk.DataVisualization");
...
const aecModelData = await viewerDocument.downloadAecModelData();
if (aecModelData) {
const levelsExt: any | Autodesk.AEC.LevelsExtension = await viewer.loadExtension("Autodesk.AEC.LevelsExtension", {
doNotCreateUI: true,
});
const floorData = levelsExt.floorSelector.floorData;
const floor = floorData[2];
levelsExt.floorSelector.selectFloor(floor.index, true);
}
const structureInfo = new Autodesk.DataVisualization.Core.ModelStructureInfo(viewer.model);
let roomDevices: Autodesk.DataVisualization.Core.RoomDevice[] = [];
devices.forEach((device) => {
let autodeskDevice: Autodesk.DataVisualization.Core.RoomDevice = {
id: device.id, // An ID to identify this device
position: device.position, // World coordinates of this device
sensorTypes: device.sensorTypes, // The types/properties this device exposes
type: "Thermometer",
};
roomDevices.push(autodeskDevice);
});
const heatmap = await structureInfo.generateSurfaceShadingData(roomDevices, undefined, "Rooms");
};
Looks your source model is RVT in Deutschland. If so, please use this code snippet instead.
const shadingdata = await structureInfo.generateSurfaceShadingData(devices, null, 'Räumen')
For RVT -> NWD/DWC, please check my blog post here Add Data Visualization Heatmaps for Rooms of non-Revit model part I - NWC
Querying Revit master views in the viewer:
const root = viewerDocument.getRoot();
const viewables = root.search({'type':'geometry', 'role': '3d'});
console.log('Viewables:', viewables);
const phaseViews = viewables.filter(v => v.data.name === v.data.phaseNames && v.getViewableRootPath().includes('08f99ae5-b8be-4f8d-881b-128675723c10'));
console.log('Master Views:', phaseViews);
// or this one if you just have one master view (phase) inside your model.
// viewerDocument.getRoot().getDefaultGeometry(true);

Increase sails bodyP

In my app (sails 0.12.0) I want to extend a limit of bytes send upon POST request. So I've followed the comments in this stackoverflow question
var skipper = require('skipper');
skipper.limit = 1024*1024*100;
middleware: {
bodyParser: skipper
}
I still get an error:
"data": {
"code": "E_EXCEEDS_UPLOAD_LIMIT",
"name": "Upload Error",
"maxBytes": 15000000,
"written": 15007474,
"message": "Upload limit of 15000000 bytes exceeded (15007474 bytes written)"
}
I've also tried to add the code below directly under module.exports.http and then I've tried to add it in the middleware only.
bodyParser: (function () {
var opts = {limit:'50mb'};
var fn;
// Default to built-in bodyParser:
fn = require('skipper');
return fn(opts);
})
My question is: Why none of these codes work and how can I increase the limit. The solution can be not elegant.
Everything that you need - set
maxBytes
attribute in object of options to upload() method of skipper Upstream.
req.file('image').upload({maxBytes: 50000000}, function (err, uploadedFiles) {
if (err) return res.serverError(err.message);
if(uploadedFiles.length > 0) {
// do with uploaded images what you want
.....
}
});

PDF Blob is not showing content, Angular 2

I have problem very similar to this PDF Blob - Pop up window not showing content, but I am using Angular 2. The response on question was to set responseType to arrayBuffer, but it not works in Angular 2, the error is the reponseType does not exist in type RequestOptionsArgs. I also tried to extend it by BrowserXhr, but still not work (https://github.com/angular/http/issues/83).
My code is:
createPDF(customerServiceId: string) {
console.log("Sending GET on " + this.getPDFUrl + "/" + customerServiceId);
this._http.get(this.getPDFUrl + '/' + customerServiceId).subscribe(
(data) => {
this.handleResponse(data);
});
}
And the handleResponse method:
handleResponse(data: any) {
console.log("[Receipt service] GET PDF byte array " + JSON.stringify(data));
var file = new Blob([data._body], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
}
I also tried to saveAs method from FileSaver.js, but it is the same problem, pdf opens, but the content is not displayed. Thanks
I had a lot of problems with downloading and showing content of PDF, I probably wasted a day or two to fix it, so I'll post working example of how to successfully download PDF or open it in new tab:
myService.ts
downloadPDF(): any {
return this._http.get(url, { responseType: ResponseContentType.Blob }).map(
(res) => {
return new Blob([res.blob()], { type: 'application/pdf' })
}
}
myComponent.ts
this.myService.downloadPDF().subscribe(
(res) => {
saveAs(res, "myPDF.pdf"); //if you want to save it - you need file-saver for this : https://www.npmjs.com/package/file-saver
var fileURL = URL.createObjectURL(res);
window.open(fileURL); / if you want to open it in new tab
}
);
NOTE
It is also worth mentioning that if you are extending Http class to add headers to all your requests or something like that, it can also create problems for downloading PDF because you will override RequestOptions, which is where we add responseType: ResponseContentType.Blob and this will get you The request body isn't either a blob or an array buffer error.
ANGULAR 5
I had the same problem which I lost few days on that.
Here my answer may help others, which helped to render pdf.
For me even though if i mention as responseType : 'arraybuffer', it was unable to take it.
For that you need to mention as responseType : 'arraybuffer' as 'json'.(Reference)
Working code
downloadPDF(): any {
return this._http.get(url, { responseType: 'blob' as 'json' }).subscribe((res) => {
var file = new Blob([res], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
}
}
Referred from the below link
https://github.com/angular/angular/issues/18586
Amit,
You can rename the filename by adding a variable to the end of the string
so saveAs(res, "myPDF.pdf");
Becomes
saveAs(res, "myPDF_"+someVariable+".pdf");
where someVariable might be a counter or my personal favorite a date time string.
This worked for me
var req = this.getPreviewPDFRequest(fd);
this.postData(environment.previewPDFRFR, req).then(res => {
res.blob().then(blob => {
console.clear();
console.log(req);
console.log(JSON.stringify(req));
const fileURL = URL.createObjectURL(blob);
window.open(fileURL, '', 'height=650,width=840');
})
});
Server side (Java/Jetty) : REST service that returns a File Response
The File Response itself will automatically be parsed into a pdf blob file by Jetty (because of the annotation #Produces("application/pdf") ), in other to be send to and read by the web client
#GET
#Path("/download-pdf/{id}")
#Produces("application/pdf")
public Response downloadPDF(#ApiParam(value = "Id of the report record")
#PathParam("id") Long id) {
ResponseBuilder response = null;
try {
PDFReportService service = new PDFReportService();
File reportFile = service.getPDFReportFile(id);
response = Response.ok((Object) reportFile);
response.header("Content-Disposition","attachment; filename="+reportFile.getName());
return response.build();
} catch (DomainException e) {
response = Response.serverError().entity("server.error");
}
return response.build();
}
Client side code (angular 2) : grab the blob and print it in a new browser tab
The key is to insure that you read the request reponse as a blob (as the server returned a blob; in my case)
Now, I tried so hard but I finally figured out that Angular 2 has not implemented any function to handle blob responses (neither res['_body'], nor res.blob() worked for me)
So I found no other workaround than using JQuery ajax to perform that file blob request, like following:
public downloadPDFFile() {
let fileURL = serverURL+"/download-pdf/"+id;
let userToken: string = your_token;
showWaitingLoader();
$.ajax({
url: fileURL,
cache: false,
headers: {
"Content-Type": "application/json",
"Authorization": "Basic " + userToken
},
xhrFields: {
responseType: 'blob' //Most important : configure the response type as a blob
},
success: function(blobFile) {
const url = window.URL.createObjectURL(blobFile);
window.open(url);
stopWaitingLoader();
},
error: function(e){
console.log("DOWNLOAD ERROR :", e);
}
});
}