I could successfully compile design automation web application with input file, as RVT and Json attached.
But I need to pass only a Json file, as input for workItem. in ForgeDesignAutomation.js, I wrote it as below. But looks like inputfile need to be stringified . Please help me to correct the syntax below.
here 'inputFile' is a Json file, I am not uploading any rvt file, as my addin takes only a json file as input, which is array of strings and return a rfa file as output.
How to stringify 'inputFile', when it is just a .json file ?
function startWorkitem()
{
var inputFileField = document.getElementById('inputFile');
if (inputFileField.files.length === 0) { alert('Please select an input file'); return; }
if ($('#activity').val() === null) { alert('Please select an activity'); return };
var file = inputFileField.files[0];
let activityId = $('#activity').val();
if (activityId == null)
{
alert('Please select an activity'); return
};
if (activityId.toLowerCase() === "myfirst_da4ractivity+dev")
{
startConnection(function () {
var formData = new FormData();
formData.append('inputFile', file);
//file is not uploading-------I think I could not pass the Json file.
//I need to pass connection ID here too.
writeLog('Uploading input file...');
$.ajax({
url: 'api/forge/designautomation/workitems',
dataType: 'json',
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function (res)
{
writeLog('Workitem started: ' + res.workItemId);
}
});
});
}
}
From your question, you have a client, that submits to your server, which then submits to Forge.
That way, how you submit to api/forge/designautomation/workitems endpoint varies on how it's expecting the data. As you have a .json file, you don't need to stringfy is, it's passed as a file. If you decide to send it as data, then stringfy and adjust to data: { your JSON data here },
Assuming the file came from your client to your server, you can then submit that JSON file to Forge as an input for your Workitem.
Related
I have an AJAX function who call a server side method, and this method call an API and it return a byte array. I want to convert this byte array in a PDF file, and then download the file. I have this code:
AJAX function:
function ObtenerF(nroF) {
debugger;
$.ajax({
type: 'POST',
url: '/De.aspx/BuscarFVW',
data: JSON.stringify({ nF: nroF }),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
debugger;
if (msg.d != null) {
window.open();
}
},
error: function () {
}
});
}
Code behind method:
[System.Web.Services.WebMethod]
public static byte[] BuscarFVW(string nF)
{
var respuesta = new Serv.L.SeL((U)HttpContext.Current.Session["UT"]).ObtenerF(nF);
if (respuesta != null)
{
File.WriteAllBytes(#"~\Content\tmp\hello.pdf", respuesta.F);
return respuesta.F;
}
else
return null;
}
I try this in the BuscarFVW method, but I can't pass a relative path as parameter in File.WriteAllBytes, and I don't know how to automatically download the new PDF file or save in the tmp folder in the project, and open a new tab with the PDF file (I can make this with an absolute path but this don't gonna work if I public the project in another server, but this work in my local with a path like C:/User/Desktop).
Any suggestion? Thank you.
You don't need to use ajax to download PDF and it's a bad habit to do so.
use can directly use a tag to download the file or iframe tag to present it.
And you can use window.location = '[your rout]';
to download the file.
I use asp.net web api for backend and a javascript client.
I use the form input to let the user select a file, and then I make an ajax request to the web api with the FormData, something like this:
var form = $('#uploadForm')[0];
var formData = new FormData(form);
$.ajax({
...
type: 'POST',
data: formData,
...
});
On the backend I receive this request, and get the data from the HttpContent object. Something like this:
try
{
if (!Request.Content.IsMimeMultipartContent("form-data"))
{
return StatusCode(HttpStatusCode.UnsupportedMediaType);
}
var result = await _blobRepository.UploadBlobs(Request.Content);
if (result != null && result.Count > 0)
{
return Ok(result);
}
return BadRequest();
}
I need to have unique file names.
How can I rename the file?
It does not matter if it is the client side, or the backend.
I am trying to send data to a database.php file by ajax. My Index file has a form which will collect a 4 digit input then sends to a js function which sends the data to my db file. At the moment the Db file is being called because I get a result in the console but the 4 digit key is not being sent. I expect I have done something wrong with the ajax script.
Any help please
function addCode(key) {
var code = document.forms[0].code;
if (code.value.length < 4) {
code.value = code.value + key;
}
if (code.value.length == 4) {
document.getElementById("message").style.display = "block";
setTimeout(alarm, 1000, code.value);
}
}
function alarm(code) {
$.ajax({
method: "POST",
url: "alarm.php",
data: code,
cache: false,
success: function(responseText) {
console.log(responseText) // show returned text in console
}
})
emptyCode();
}
function emptyCode() {
document.forms[0].code.value = "";
}
The issue is because you're just sending the value by itself with no key. To fix this you could provide data with an object that will be form encoded when the request is sent:
data: { code: code },
Then in your PHP code you can retrieve the posted value by its key:
$code = $_POST['code'];
My goal is to pass a file to my backend which runs on laravel. The file is drag and dropped on the web page and not my input file. I went through the previous issues on stack overflow and fixed my code accordingly but still the issue exists.
Here is my javascript code that uses ajax to pass the file
$("html").on("drop", function (e) {
e.preventDefault();
e.stopPropagation();
var dt = e.dataTransfer || (e.originalEvent && e.originalEvent.dataTransfer);
var files = e.target.files || (dt && dt.files);
if (files) {
for (var i = 0; i < e.originalEvent.dataTransfer.files.length; i++) {
var file_ext = e.originalEvent.dataTransfer.files[i].name.split('.').pop();
console.log(file_ext);
if ((file_ext == 'pdf') || (file_ext == 'docx') || (file_ext == 'txt')) {
console.log('right file');
var resume = e.originalEvent.dataTransfer.files[i].value;
var form_data = new FormData();
form_data.append("resume", resume);
var resume_val = e.originalEvent.dataTransfer.files[i].name;
console.log(form_data);
var token = $('#token').val()
var hello = "hello";
$.ajax({
url: '/resume_upload',
type: 'POST',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: ({
resume: form_data,
wish: "Naveen its working"
}),
success: function (data) {
console.log(data.msg);
alert(data.msg);
},
error: function (xhr, status, error) {
console.log(error);
alert(error)
}
});
} else {
console.log('wrong file');
}
}
} else {
console.log('file not recieved');
}
});
Here is where i get the file
var resume = e.originalEvent.dataTransfer.files[i].value;
var form_data = new FormData();
form_data.append("resume",resume);
But when i console.log(form_data) it logged FormData{} just empty form data. So obviously i pass nothing with my ajax function. Am i doing anything wrong in getting the file ? I don't have an idea how to go about this.
Maybe I misunderstood what do you want but I think you should do stg like this:
var form_data = new FormData();
form_data.append('resume_file_name', e.originalEvent.dataTransfer.files[i].value);
form_data.append('resume_file', e.originalEvent.dataTransfer.files[i]);
form_data.append('wish', "Naveen its working");
if u want to upload the file, not just some file info
and with FormData, you can pass all the data you want, so just pass this to $.ajax data parameter:
data: form_data,
and there is something else, may this was the original problem:
when jQuery handles the parameters it also tries to convert it, but this causes problems, when pass a FormData type to data attribute, so you should also add these parameters to the $.ajax input object:
processData: false,
contentType: false
parameters.
Sorry for my bad english!
var values = $('#form_field').serialize();
dataS = "val="+values;
$.ajax({
type: "POST",
url: URL,
data: dataS,
cache: false,
dataType: 'json',
success: function(response)
{ },
});
But the form has an (<input type="file"> field) how do I pass the file into the form using this ajax serialization method. When I print $_FILES doesn't getting any output.
You can't past the $_FILES variable when using ajax. I can assure you that. Thanks.
Ajax does not support file uploads, you should use iframe instead.
you can check further detail here
Posting via Ajax file upload isn't straight forward. First, it isn't directly doable using XHR1.
There are two main ways to do the uploads, using a frame and using the XHR2 spec and the FormData object. This is the method I would recommend.
The easiest way to do this is then to perform two uploads. I'm going to borrow some code here, from GitHub user optikalefx to show you how to do it using jQuery:
// Ajax File upload with jQuery and XHR2
// Sean Clark http://square-bracket.com
// xhr2 file upload
// data is optional
$.fn.upload = function(remote,data,successFn,progressFn) {
// if we dont have post data, move it along
if(typeof data != "object") {
progressFn = successFn;
successFn = data;
}
return this.each(function() {
if($(this)[0].files[0]) {
var formData = new FormData();
formData.append($(this).attr("name"), $(this)[0].files[0]);
// if we have post data too
if(typeof data == "object") {
for(var i in data) {
formData.append(i,data[i]);
}
}
// do the ajax request
$.ajax({
url: remote,
type: 'POST',
xhr: function() {
myXhr = $.ajaxSettings.xhr();
if(myXhr.upload && progressFn){
myXhr.upload.addEventListener('progress',function(prog) {
var value = ~~((prog.loaded / prog.total) * 100);
// if we passed a progress function
if(progressFn && typeof progressFn == "function") {
progressFn(prog,value);
// if we passed a progress element
} else if (progressFn) {
$(progressFn).val(value);
}
}, false);
}
return myXhr;
},
data: formData,
dataType: "json",
cache: false,
contentType: false,
processData: false,
complete : function(res) {
var json;
try {
json = JSON.parse(res.responseText);
} catch(e) {
json = res.responseText;
}
if(successFn) successFn(json);
}
});
}
});
};
I should also note that browser support for this is a little more limited, despite XHR2 being around for 2 years now: https://developer.mozilla.org/en-US/docs/Web/API/FormData contains more information as well as a Browser compatibility chart.