file upload in javascript and send file through api - javascript

I'm trying to upload a file and send that via api as a file.But not getting working. Here is my used for upload and send my file to api.
But it most probably terns to the error message.
$(document).on('change', '#txtUploadFile', function(e){
var files = e.target.files;
if (files.length > 0) {
if (this.value.lastIndexOf('.xlsx') === -1){
alert('Only ods files are allowed!');
this.value = '';
return;
}
if (window.FormData !== undefined) {
var data = new FormData();
for (var x = 0; x < files.length; x++){
data.append("file" + x, files[x]);
}
$.ajax({
type: "POST",
contentType: "multipart/form-data",
url: 'http://localhost/clicportaltest/rest/clicadmin/uploadExcel',
data:{file:file},
success: function(result) {
console.log(result);
},
error: function (xhr, status, p3, p4){
var err = "Error " + " " + status + " " + p3 + " " + p4;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).Message;
console.log(err);
}
});
} else {
alert("This browser doesn't support HTML5 file uploads!");
}
}
});

$(function(){
$('#submitUpload').on('click', function(){
var file = document.getElementById("upload").files[0];
var form = new FormData();
form.append("file", file);
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost/clicportaltest/rest/clicadmin/uploadExcel",
"method": "POST",
"processData": false,
"contentType": false,
"mimeType": "multipart/form-data",
"data": form
};
$.ajax(settings).done(function (response) {
console.log(response);
});
});
});

You can't JSON.stringify data because FormData doesn't have a toJSON() method, so it is treated as a plain object which results in "{}".
You can either implement your own FormData.prototype.toJSON method or just convert data to a string or a plain object in your handler. How the stringified representation of data should be formatted depends entirely on how your API expects it to be.

Related

Failed to load PDF but can see the data

I am getting this error that Chrome failed to load the PDF document. I can see the content of the data is the console window so I have the data being returned I just not sure why it will not display? If I File.WriteAllBytes to disk it will open fine so it maybe something with the creating the new Blob
Failed to load PDF document.
ts code
printItems(versionKeys: string[]): JQueryPromise<any> {
console.log('printItems');
$.ajax({
type: "post",
contentType: "application/json",
data: JSON.stringify(versionKeys),
url: this.apiUrls.PrintTemplates,
success: function (data, status, xhr) {
console.log('printItems');
console.log(data);
let blob = new Blob([data.Content], { type: data.ContentType });
var url = URL.createObjectURL(blob);
console.log(url);
window.open(url);
console.log('success');
}
});
return;
}
Error
I converted the base64 string to a bytes
var binary_string = window.atob(data.Content)
var len = data.Content.length;
var bytes = new Uint8Array(len);
for (var i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i);
}
let blob = new Blob([bytes.buffer], { type: data.ContentType })
var url = URL.createObjectURL(blob);
window.open(url);

Accessing the Forge Viewer From Two HTML Files

I have been working on a website incorporating the autodesk-forge viewer (more details can be seen on my past questions). I have successfully made many autodesk-forge viewer functions in a standard javascript (.js) file. These functions include displaying the viewer, and isolating to a particular part, when an external button is pressed.
Currently I have a main html/php home page where I have included my javascript file with all my forge functions using <script src="MyForgeFunctions.js"></script>
These functions are accessed through a button, which successfully displays the viewer in the html page. Attached to my main php/html page, another html/php page was added through an iframe html reference (<iframe src="URL.php"></iframe>). My home page displays the main machines we make, while the embedded php/html page displays all the stations within the machine. I have also included the MyForgeFunctions.js inside this second php/html page. Because of the way the website is set up, I need to be able to access the viewer in both web pages. However, when I attempt to access the viewer from the second html page, I get a message that the viewer is undefined. Below is my code from MyForgeFunctions.js.
var ext = '';
var dim = '';
var assemblyname = '';
function getAssemblyName(){
assemblyname = sessionStorage.getItem("assemblyName");
//var ext = partname.substr(partname.lastIndexOf('.'));
ext = assemblyname.split('.');
dim = ext[0] + ':1';
console.log(assemblyname);
console.log(dim);
if (dim !== ''){
isolateSelected();
}
}
//function to get part name from __MachineParts.php
var partname = '';
var extension = '';
var namewithoutextension = '';
function getPartName(){
partname = sessionStorage.getItem("partName");
//var ext = partname.substr(partname.lastIndexOf('.'));
extension = partname.split('.');
namewithoutextension = extension[0] + ':1'
console.log(partname);
console.log(namewithoutextension);
if (namewithoutextension !== ''){
isolateSelectedPart();
}
}
/*******************************************************************************
*
* AUTODESK FORGE VIEWER CODE (HTTP REQUESTS)
*
*******************************************************************************/
//VARIABLE DECLARATION
var code = '';
var access_token = '';
const hub = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx';
const project ='xxxxxxxxxxxxxxxxxxxxxxxxxxx';
const folder='xxxxxxxxxxxxxxxxxxxxxxxxx';
const item = 'xxxxxxxxxxxxxxxxxxxxxxxxx';
var itemid = '';
var urn = '';
var urn2 = '';
//allow the program to view data from autodesk
function authorize(){
window.location.href = "https://developer.api.autodesk.com/authentication/v1/authorize?response_type=code&client_id=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&redirect_uri=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&scope=data:read data:write bucket:read viewables:read bucket:create data:create";
}
//grab the code from the url
function getCode(){
const querystring = window.location.search;
// console.log(querystring);
const urlParams = new URLSearchParams(querystring);
code = urlParams.get('code');
// console.log(code);
}
//call the function to get the code right away, and obtain a token
getCode();
getToken();
//function to obtain access token
function getToken(){
$.ajax({
method: 'POST',
url: 'https://developer.api.autodesk.com/authentication/v1/gettoken',
headers: {
'Content-Type':'application/x-www-form-urlencoded'
},
data:'client_id=dm2VLfnwJ6rYHKPAg7dG6l9yVbBQPGlH&client_secret=HRMpOPusLhsVoIMk&grant_type=authorization_code&code=' + code + '&redirect_uri=http://team/__MachineViewerMV.php',
success:function(response){
// console.log(response);
access_token = response.access_token;
console.log(access_token);
}
})
}
//Grab desired file id from project folder
function getItem(){
$.ajax({
method:'GET',
url: 'https://developer.api.autodesk.com/data/v1/projects/' + project + '/folders/' + item + '/contents',
headers:{
Authorization:'Bearer ' + access_token
},
/* beforeSend:function(before){
if(access_token !== '' && viewer !==''){
destroyViewer();}
},*/
success:function(response){
//console.log(response);
// folder = response.data[0].id;
// console.log(folder);
// itemid = response.data[0].id;
//console.log(itemid);
console.log(response);
for (var i = 0; i<response.data.length; i++){
//console.log(response.data[i].attributes.displayName);
if(response.data[i].attributes.displayName == fileName){
//console.log('hooray');
itemid = response.data[i].id;
console.log(itemid);
getVersion();
break;
}
else if (response.data[i].attributes.displayName !== fileName){
itemid = '';
}
}
},
error:function(error){
authorize();
}
})
}
function get2dItem(){
$.ajax({
method:'GET',
url: 'https://developer.api.autodesk.com/data/v1/projects/' + project + '/folders/' + item + '/contents',
headers:{
Authorization:'Bearer ' + access_token
},
/*beforeSend:function(before){
if(access_token !== '' && viewer !== ''){
destroyViewer();}
},*/
success:function(response){
//console.log(response);
// folder = response.data[0].id;
// console.log(folder);
// itemid = response.data[0].id;
//console.log(itemid);
console.log(response);
for (var i = 0; i<response.data.length; i++){
//console.log(response.data[i].attributes.displayName);
if(response.data[i].attributes.displayName == fileName2d){
//console.log('hooray');
itemid = response.data[i].id;
console.log(itemid);
getVersion();
break;
}
else if (response.data[i].attributes.displayName !== fileName2d){
itemid = '';
}
}
},
error:function(error){
authorize();
}
})
}
//get version of the file using its id
function getVersion(){
$.ajax({
method:'GET',
url: 'https://developer.api.autodesk.com/data/v1/projects/' + project + '/items/' + itemid + '/versions',
headers:{
Authorization:'Bearer ' + access_token
},
success:function(response){
//console.log(response);
urn = btoa(response.data[0].relationships.storage.data.id);
console.log(urn);
translateToSVF();
}
})
}
function translateToSVF(){
$.ajax({
method: 'POST',
url:"https://developer.api.autodesk.com/modelderivative/v2/designdata/job",
headers:{
"content-type": "application/json",
Authorization: "Bearer " + access_token
},
data:JSON.stringify({
"input":{ "urn":urn
},
"output": {
"formats": [
{
"type": "svf",
"views": [
"2d",
"3d"
]
}
]
}
}),
success:function(response){
// console.log(response);
urn2 = response.urn;
console.log(urn2);
checkStatus();
}
})
}
function checkStatus(){
$.ajax({
method: 'GET',
url: "https://developer.api.autodesk.com/modelderivative/v2/designdata/" + urn2 + "/manifest",
headers:{
Authorization: "Bearer " + access_token
},
success: function(response){
console.log(response);
if (response.progress == 'complete'){
displayViewer();
}
else if (response.progress !== 'complete'){
alert('File Still Uploading, Press the Display Button Again!');
}
}
})
}
//function to get list of viewables\
var guid = '';
function getViewable(){
$.ajax({
method:'GET',
headers:{
Authorization: "Bearer " + access_token
},
url: 'https://developer.api.autodesk.com/modelderivative/v2/designdata/' + urn2 + '/metadata',
success:function(response){
console.log(response);
guid = response.data.metadata[0].guid;
console.log(guid);
}
})
}
//funciton to get the list of items within a model
function getTree(){
$.ajax({
method: 'GET',
headers:{
Authorization: "Bearer " + access_token
},
url:'https://developer.api.autodesk.com/modelderivative/v2/designdata/' + urn2 + '/metadata/' + guid + '/properties',
success:function(response){
console.log(response);
}
})
}
/**********************************************************************************
*
* FUNCTION TO DISPLAY THE VIEWER IN THE HTML PAGE
*
**********************************************************************************/
var viewer;
function displayViewer(){
//var viewer;
var options = {
env: 'AutodeskProduction',
api: 'derivativeV2', // for models uploaded to EMEA change this option to 'derivativeV2_EU'
getAccessToken: function(onTokenReady) {
var token = access_token;
console.log(token);
var timeInSeconds = 3600; // Use value provided by Forge Authentication (OAuth) API
onTokenReady(token, timeInSeconds);
}
};
Autodesk.Viewing.Initializer(options, function() {
var htmlDiv = document.getElementById('forgeViewer');
viewer = new Autodesk.Viewing.Private.GuiViewer3D(htmlDiv);
var startedCode = viewer.start();
// sessionStorage.setItem("viewer", viewer);
if (startedCode > 0) {
console.error('Failed to create a Viewer: WebGL not supported.');
return;
}
console.log('Initialization complete, loading a model next...');
});
var documentId = 'urn:'+urn2;
Autodesk.Viewing.Document.load(documentId, onDocumentLoadSuccess, onDocumentLoadFailure);
function onDocumentLoadSuccess(viewerDocument) {
var defaultModel = viewerDocument.getRoot().getDefaultGeometry();
viewer.loadDocumentNode(viewerDocument, defaultModel);
console.log(viewer);
}
function onDocumentLoadFailure() {
console.error('Failed fetching Forge manifest');
}
}
//function to hide the viewer
function destroyViewer(){
console.log(viewer);
viewer.finish();
viewer = null;
Autodesk.Viewing.shutdown();
}
/*****************************************************************************
* FUNCTIONS TO MODIFY THE VIEWER TO ZOOM INTO THE CORRECT PART/ASSEMBLY
*/
function isolateSelected(){
console.log(dim);
console.log(viewer);
viewer.search(dim, function(dbIds) {
// viewer.search('"' + 'M-109408 FOLDING PLOUGH:2' + '"', function(dbIds) {
console.log(dbIds.length);
getSubset(dbIds, 'label', dim, function(dbIds) {
// getSubset(dbIds, 'label', 'M-109408 FOLDING PLOUGH:2', function(dbIds) {
// getSubset(dbIds, property.name, 'M-54439 POST TUBING:1', function(dbIds) {
//getSubset(dbIds, property.name, property.value, function(dbIds){
var it = viewer.model.getData().instanceTree;
//console.log(it);
for (i = 0; i<dbIds.length; i++){
var namepart = it.getNodeName(dbIds[i]);
if (namepart !== undefined){
console.log(dbIds);
console.log(namepart);}}
/* for (i = 121; i<381;i++){
var dbId = i;
var it = NOP_VIEWER.model.getData().instanceTree;
var name = it.getNodeName(dbId);
console.log(name);}*/
viewer.isolate(dbIds)
viewer.select(dbIds);
viewer.utilities.fitToView();
})
}, function(error) {})
}
function isolateSelectedPart(){
console.log(namewithoutextension);
viewer.search(namewithoutextension, function(dbIds) {
// viewer.search('"' + 'M-109408 FOLDING PLOUGH:2' + '"', function(dbIds) {
console.log(dbIds.length);
getSubset(dbIds, 'label', namewithoutextension, function(dbIds) {
// getSubset(dbIds, 'label', 'M-109408 FOLDING PLOUGH:2', function(dbIds) {
// getSubset(dbIds, property.name, 'M-54439 POST TUBING:1', function(dbIds) {
//getSubset(dbIds, property.name, property.value, function(dbIds){
var it = viewer.model.getData().instanceTree;
//console.log(it);
for (i = 0; i<dbIds.length; i++){
var namepart = it.getNodeName(dbIds[i]);
if (namepart !== undefined){
console.log(dbIds);
console.log(namepart);}}
/* for (i = 121; i<381;i++){
var dbId = i;
var it = NOP_VIEWER.model.getData().instanceTree;
var name = it.getNodeName(dbId);
console.log(name);}*/
viewer.isolate(dbIds)
viewer.select(dbIds);
viewer.utilities.fitToView();
})
}, function(error) {})
}
//function to find the dbid of the part/assembly
function getSubset(dbIds, name, value, callback) {
console.log("getSubset, dbIds.length before = " + dbIds.length)
viewer.model.getBulkProperties(dbIds, {
propFilter: [name],
ignoreHidden: true
}, function(data) {
var newDbIds = []
for (var key in data) {
var item = data[key]
// console.log(item.properties);
if (item.properties[0].displayValue === value) {
newDbIds.push(item.dbId)
}
}
console.log("getSubset, dbIds.length after = " + newDbIds.length)
callback(newDbIds)
}, function(error) {})
}
Because of how the webpage is set up, when I needed to use a variable from the second web page in the first, I used sessionStorage.getItem and sessionStorage.setItem. I have also made a simple function as so inside MyForgeFunctions.js:
function checkViewer(){
console.log(viewer);
}
I then included a button in both html pages to execute the function with an onclick event. When the function is run from the first/home html page the following is displayed:
T {globalManager: e, clientContainer: div#forgeViewer, container: div.adsk-viewing-viewer.notouch.dark-theme.quality-text, config: {…}, contextMenu: o, …}. Which is normal for the viewer, but when the function is executed from the second html page, the viewer is undefined. Any help as to why this is happening or any solutions will be greatly appreciated. Cheers!
From the iframe, in order to access the viewer inside the main web page, I had to use (parent.viewer).

save image in folder using jquery ajax in c#?

I am able to send data on .cs page and image also save in folder but it's corrupted and image size is 0.. i am totally confused that where is the error
Please see the JQUERY CODE & C# CODE also
JQUERY code
<script type="text/javascript">
$(document).ready(function () {
$("#submitPhoto").click(function () {
var photo = $("#uploadPhoto").get(0);
var file = photo.files;
var Photo_Path = $("#uploadPhoto").val();
var extenssion = Photo_Path.split('.').pop().toUpperCase();
if (Photo_Path == "") {
alert('Please Choose Photo');
return;
}
if (extenssion != 'JPEG' && extenssion != 'JPG' && extenssion != 'jpg') {
alert('Invalid File[JPEG,JPG is acceptable]');
return;
}
if (file.size < 4000 || file.size > 14000) {
alert('Photo Size Must be Below 12Kb and Above 4Kb ');
return;
}
var id = $("#submitPhoto").attr('id');
$.ajax({
type: "POST",
contentType: "multipart/form-data",
url: "finalstep-registration.aspx?photoPath=" + Photo_Path + "&id=" + id + "&check=imgUpload",
data: file,
datatype: 'json',
async: false,
processData: false,
success: function (data) {
alert('Image successfully Uploaded');
},
error: function ()
{ console.log('there is some error'); }
});
});
</script>
C# code
By which image are save in folder and name are save in database
I am calling uploadPhoto()function on pageload using query string
public void uploadPhoto(string photoPath,string id)
{
//HttpContext context = HttpContext.Current;
//int regNo = Convert.ToInt32(Session["restrationNumber"].ToString());
int regNo = 1001;
if (id == "submitPhoto")
{
FileInfo CustPic = new FileInfo(photoPath);
System.IO.Stream fileContent = Request.InputStream;
FileStream fileStream = File.Create(Server.MapPath("~/photo/") + CustPic.Name);
fileContent.Seek(0, System.IO.SeekOrigin.Begin);
fileContent.CopyTo(fileStream);
//System.Web.Hosting.HostingEnvironment.MapPath("~/photo/");
string query = "update userDetails set photo='"+photoPath+ "' where regNo="+regNo+"";
int a = bl.executenonquery(query);
if (a == 1)
Response.Write("Photo is uploaded successfully");
else
Response.Write("Oops, We can't upload your photo. try again");
//Session["photo"] = CustPic.Name;
}
}
Check and tell me where i am doing wrong

how receive json in jquery success method and use that json to build html content

I am working on an java spring application that requires the controller to return json. By receiving that json in jquery success method, I want to make html out of it.
controller returns a json like below:
return "[{\"Id\": \"1\", \"Name\": \"Apples\"}, {\"Id\": \"2\", \"Name\":\"Mangoes\"}]";
jquery used to hit that controller and then receive the json in success method:
var content;
$(document).ready(function(){
$("#submitButton").click(function(e){
var formData = getFormData();
if(formData!=false){
$.ajax({
type: 'POST',
'url': 'http://localhost:8080/Test_ReportingUI/fieldMappingNext.htm',
data: {jsonData: JSON.stringify(formData)},
dataType: 'json',
success: function(response){
for (var x = 0; x < response.length; x++) {
content = response[x].Id;
content += "<br>";
content += response[x].Name;
content += "<br>";
$(content).appendTo("#Fruits");
}
},
timeout: 10000,
error: function(xhr, status, err){
if(response.status=='timeout')
{
alert('Request time has been out','');
}
console.log(status,err);
}
}); }
});
});
below is the HTML div where I want to use above content to append:
<div id="Fruits">
fruits :
</div>
it is reaching to the controller. and also returning json. but I am not able to use that json.
Replace your for loop with
for (var x = 0; x < response.length; x++)
{
content = "<div class='fruit'><div>" + response[x].Id + "</div>";
content += "<div>" + response[x].Name + "</div></div>";
$(content).appendTo("#Fruits");
}
Your error message correctly explained that you were not appending the correct expression into the fruits
try below code
$(document).ready(function() {
$("#submitButton").click(function(e) {
var formData = getFormData();
if (formData != false) {
$.ajax({
type: 'POST',
'url': 'http://localhost:8080/Test_ReportingUI/fieldMappingNext.htm',
data: {
jsonData: JSON.stringify(formData)
},
dataType: 'json',
success: function(response) {
for (var x = 0; x < response.length; x++) {
var fContent = $("<div></div>");
var id = $("<span></span>").text(response[x].Id);
var name = $("<span></span>").text(response[x].Name);
fContent.append(id)
fContent.append(name);
$("#Fruits").append(fContent);
}
},
timeout: 10000,
error: function(xhr, status, err) {
if (response.status == 'timeout') {
alert('Request time has been out', '');
}
console.log(status, err);
}
});
}
});
});

Facebook photo upload with JavaScript is not working

I need to write a javascript code for construct 2 plugin. below is my code :
Acts.prototype.PublishToWallPHOTO = function (snapshotdata)
{
if (this.runtime.isDomFree || !fbLoggedIn)
return;
var blob;
try
{
blob = dataURItoBlob(snapshotdata.replace("data:image/png;base64,", ""),'image/png');
}
catch(e){console.log(e);}
FB.api('/me/photos', 'POST', {
message:'photo description',
source:blob
}, function(response) {
if (!response || response.error)
console.error(response);
});
};
function dataURItoBlob(dataURI,mime)
{
var byteString = window.atob(dataURI);
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
var blob = new Blob([ia], { type: mime });
return blob;
}
for above code parameter for "snapshotdata" look like this : "data:image/png;base64,iVBORw0KGgoAAAA.........."
But my image was not uploaded to facebook using above code. but with same code if I use url:'http://example.com/abc.png' instead of source:blob then it upload a image in given URL successfully. I was tried to find the wrong with above code, but i was unable to find a proper solution. Please tell me if any one know the issue with above code.
ps: sorry for poor English
Maybe a FormData() does the trick.
function uploadPicture(response) {
if (response.status === 'connected') {
var blob = dataURItoBlob(imageHolder.imageElement.dom.src.replace("data:image/png;base64,", ""),'image/png');
var fd = new FormData();
var token = response.authResponse.accessToken;
fd.append("access_token",token);
fd.append("source\"; filename=\"" + "test.png" + "\"", blob);
fd.append("message","Test");
try{
$.ajax({
url:"https://graph.facebook.com/me/photos?access_token=" + token,
type:"POST",
data:fd,
processData:false,
contentType:false,
cache:false,
success:function(data){
console.log("success " + data);
},
error:function(shr,status,data){
console.log("error " + data + " Status " + shr.status);
},
complete:function(){
console.log("Ajax Complete");
}
});
}catch(e){console.log(e);}
}
}

Categories