Load external JSON data via API into PDF file form field - javascript

I have a button inside a PDF file which when clicked should call an API and write the data into a form field. Inside the Acrobat Reader Debugger I get the 'undefined' error. What am I missing?
FYI I have changed the API key...
var API = "https://api.openweathermap.org/data/2.5/weather?q=Berlin&units=metric&lang=de&appid=860b8e982b1aecb176f5aee385c73be0"
var getData = app.trustedFunction(function (cURL) {
app.beginPriv();
var params = {
cVerb: "GET",
cURL: cURL,
oHandler: {
response: function (msg, uri, e) {
var stream = msg;
var string = "";
string = SOAP.stringFromStream(stream);
var data = eval("(" + string + ")");
}
}
};
Net.HTTP.request(params);
app.endPriv();
});
getData(API);
getField('1').value = data.main.temp;

Related

How to upload multiple images from front-end using JavaScript, jQuery, Ajax in JSP file and send it into Spring Boot Controller?

I am working on a spring boot web application, where I want to upload multiple images of a product at a time along with other fields (for example product name, SKU code, category, tags, subcategory, etc). I have written code for RESTful API to upload multiple images and it is working perfectly for me. I tested API using postman and it is working fine. But, I don't know how to do it from the front end. I am showing you my front-end code below, where I am sending a single image to my controller using Ajax.
$("#file").change(function(){
var formData = new FormData();
var fileSelect = document.getElementById("file");
if(fileSelect.files && fileSelect.files.length == 1) {
var file = fileSelect.files[0];
formData.set("file",file,file.name);
}else{
$("#file").focus();
return false;
}
var request = new XMLHttpRequest();
try {
request.onreadystatechange=function() {
if(request.readyState==4) {
var v = JSON.parse(request.responseText);
if(v.status==="OK") {
alert("Product Image Uploaded Successfully")
document.getElementById('imagepath').value = v.response;
}
}
}
request.open('POST',"<%=AkApiUrl.testuploadfile%>");
request.send(formData);
} catch(e) {
swal("Unable to connect to server","","error");
}
});
As I told you, the above code is to send a single file at a time. I am showing you my API controller code also:
#RequestMapping(value = AkApiUrl.testuploadfile, method = { RequestMethod.POST, RequestMethod.GET }, produces = {MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity<?> testuploadfile(HttpServletRequest request, #RequestParam("files") MultipartFile[] files) {
CustomResponse = ResponseFactory.getResponse(request);
String imgurl = "NA";
try {
String path = Constants.webmedia;
String relativepath = "public/media/";
System.out.println("Here is the image: ");
List<MultipartFile> multifile = Arrays.asList(files);
if( null != multifile && multifile.size()>0) {
for (int i=0; i < multifile.size(); i++) {
String filename = files[i].getOriginalFilename();
String extension = filename.substring(filename.lastIndexOf("."), filename.length());
int r = (int )(Math.random() * 500 + 1);
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmss");
Date date = new Date();
String formatdate = format.format(date);
formatdate = "ECOM" + formatdate + r;
byte[] bytes = files[i].getBytes();
BufferedOutputStream stream = new BufferedOutputStream( new FileOutputStream(new File(path + File.separator + formatdate + extension)));
stream.write(bytes);
stream.flush();
stream.close();
String newimgurl = relativepath + formatdate + extension;
imgurl = imgurl+"##"+newimgurl;
if(imgurl != null) {
CustomResponse.setResponse(imgurl);
CustomResponse.setStatus(CustomStatus.OK);
CustomResponse.setStatusCode(CustomStatus.OK_CODE);
}
}
}
} catch (Exception e) {
e.printStackTrace();
CustomResponse.setResponse(null);
CustomResponse.setStatus(CustomStatus.Error);
CustomResponse.setStatusCode(CustomStatus.Error_CODE);
CustomResponse.setResponseMessage(CustomStatus.ErrorMsg);
}
return new ResponseEntity<ResponseDao>(CustomResponse, HttpStatus.OK);
}
This API is working fine, I am getting desired response. But I do not know how should I implement this thing on the JSP page. Please, any suggestions would be appreciated.

data modified after send with ajax

I am using javascript and the Flask framework
I would like to retrieve in Flask in python the bytes of one or more files that the user will have chosen in my HTML page. To do this, when the user has chosen the files and has clicked on the send button, it triggers a function that uses the FileReader API to retrieve the base64 content of the file(s) that the user has selected.
After that, I would like to send the base64 data to flask with ajax.
But here is my problem, when I get the base64 string in python and compare it with the one in javascript, I notice the number of characters is exactly the same, but some characters are different as you can see on the screenshots below
size of character strings
And when I decode the base64 string, I get different bytes :
bytes variables
This makes me think that the problem is with the use of ajax
Code Python :
#app.route('/test', methods=['POST'])
def test():
if request.method == "POST":
files = eval(request.form.get("files"))
python_data = file.get("data")
javascript_data = "" # Copy from chrome console
len_python_data = len(python_data)
len_javascript_data = len(javascript_data)
base64_bytes_javascript = base64.b64decode(javascript_data)
base64_bytes_python = base64.b64decode(python_data)
Code Javascript :
let array_files = [];
let files_input = document.getElementById("files_input");
let files = files_input.files;
let reader = new FileReader();
function readFile(index) {
if( index >= files.length ) {
let data = "files=" + JSON.stringify(array_files);
$.ajax({
url: '/test',
type: 'POST',
data: data,
success: function (msg) {
console.log(msg)
}
});
return;
}
let file = files[index];
reader.name = file.name;
reader.onload = function() {
let file_info = {};
// get file content
let bin = this.result;
console.log(bin)
let data = bin.split(";")[1].replace("base64,", "");
file_info.name = reader.name;
file_info.data = data;
array_files.push(file_info);
readFile(index + 1)
}
reader.readAsDataURL(file);
}
readFile(0);
The problem is solved
In the base64 character string, the "+" were replaced by spaces after sending it to ajax.

How to attach a PDF generated using jsPDF to the mail using asp.net c#

I need to know if there is any way to attach a PDF file generated using jsPDF and mail it in asp.net C#?
I have the following code in c#
MailMessage message = new MailMessage(fromAddress, toAddress);
message.Subject = subject;
message.IsBodyHtml = true;
message.Body = StrContent.ToString();
//message.Attachments.Add(new Attachment("getDPF()"));
smtp.Send(message);
and I'm using a JsPDF library as follows:
<script type="text/javascript" src="jsPdf/jspdf.min.js"></script>
<script type="text/javascript">
function getPDF()
{
var doc = new jsPDF();
doc.text(20, 20, 'TEST Message');
doc.addPage();
//doc.save('volt.pdf');
}
</script>
Is there any way to attach it in the mail before send it?
Thanks in advance.
You cannot call client-side code (Javascript function) from server code (c#).
You can only communicate via the (HTTP/HTTPs) protocol.
I think you need to generate the PDF from the client and then send that PDF to server so that you can attach the PDF to an email.
In that case you need to first generate the PDF and send it to the server as a base64 string.
You can then convert the base64 string to PDF in C# and mail it as an attachment.
Client Side:
function generatePdf() {
var doc = new jsPdf();
doc.text("jsPDF to Mail", 40, 30);
var binary = doc.output();
return binary ? btoa(binary) : "";
}
Posting the base64 pdf content to the server:
var reqData = generatePdf();
$.ajax({
url:url,
data: JSON.stringify({data:reqData}),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success:function(){}
});
On the server (MVC Controller):
public ActionResult YourMethod(string data)
{
//create pdf
var pdfBinary = Convert.FromBase64String(data);
var dir = Server.MapPath("~/DataDump");
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
var fileName = dir + "\\PDFnMail-" + DateTime.Now.ToString("yyyyMMdd-HHMMss") + ".pdf";
// write content to the pdf
using (var fs = new FileStream(fileName, FileMode.Create))
using (var writer = new BinaryWriter(fs))
{
writer.Write(pdfBinary, 0, pdfBinary.Length);
writer.Close();
}
//Mail the pdf and delete it
// .... call mail method here
return null;
}
Check out here for more information https://github.com/Purush0th/PDFnMail
Your code example use pdf.text(), but in most situations, you want to export a html page with table(s) or image(s). The latest version jsPDF html PlugIn instead of addHtml(). Below is an code example using jsPDF html() and Web API.
Client side:
function emailHtml() {
let pdf = new jsPDF('p', 'pt', 'a3'); // a4: part of the page is cut off?
pdf.html(document.body, {
callback: function (pdf) {
let obj = {};
obj.pdfContent = pdf.output('datauristring');
var jsonData = JSON.stringify(obj);
$.ajax({
url: '/api/jspdf/html2pdf',
type: 'POST',
contentType: 'application/json',
data: jsonData
});
}
});
}
Note that the datauristring returned from pdf.html has a filename added to the string, filename=generated.pdf;. Also, SmtpClient is obsolete, consider to use MailKit instead.
[Route("[action]")]
[HttpPost]
public void Html2Pdf([FromBody] JObject jObject)
{
dynamic obj = jObject;
try
{
string strJson = obj.pdfContent;
var match = Regex.Match(strJson, #"data:application/pdf;filename=generated.pdf;base64,(?<data>.+)");
var base64Data = match.Groups["data"].Value;
var binData = Convert.FromBase64String(base64Data);
using (var memoryStream = new MemoryStream())
{
var mail = new MailMessage
{
From = new MailAddress("[FromEmail]")
};
mail.To.Add("");
mail.Subject = "";
mail.Body = "attached";
mail.IsBodyHtml = true;
mail.Attachments.Add(new Attachment(new MemoryStream(binData), "htmlToPdf.pdf"));
var SmtpServer = new SmtpClient("[smtp]")
{
Port = 25,
Credentials = new NetworkCredential("[FromEmail]", "password"),
EnableSsl = true
};
SmtpServer.Send(mail);
}
}
catch (Exception ex)
{
throw;
}
}

Incomplete Form Data in ajax request

Stucked in this situation:
I upload several inputs fields and images using ajax. Images are encoded to base64 string with FileReader api.
Everything seems to work except sending encoded images.
My code (simplified):
var groups = {},
objects = {};
objects["name"] = {},
objects["group"] = {};
objects["image"] = {};
var objectCount = $(".layout-object").length;
$(".layout-object").each(function(i,v) {
var k = objectCount-i;
objects["name"][i] = $(v).val();
objects["group"][i] = $("#set-object-dropdown-"+k).val();
// get an image
var file = document.getElementById('image-'+k).files[0];
var reader = new FileReader();
reader.onload = function(event) {
objects["image"][i] = event.target.result; // get image in base64
};
reader.readAsDataURL(file);
});
$(".layout-group").each(function(i,v) {
groups[i] = $(v).val();
});
// prepare object for ajax request...
var data = {
name: $("#name").val(),
groups: groups,
objects: objects
};
// console log shows all data correctly in place = in objects there is a propery "image"...
console.log(data);
// sending ajax POST request
var posting = $.post( location.href, { data: data } );
posting.done(function(response){
console.log(response);
});
Issue: in ajax request form data property "image" is missing, but before posting object with data is correct.
Maybe is there a problem with readAsDataURL function and its onload event?
Something like this:
reader.onload = function(event) {
objects["image"][i] = event.target.result; // get image in base64
if (k == 1) //when the last object is iterated and it's image is set:
{
fireAjax();
}
};
function fireAjax(){
// sending ajax POST request
var posting = $.post( location.href, { data: data } );
posting.done(function(response){
console.log(response);
});
}

Not able to load the response

var soapre1 = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:glob=\"http://sap.com/xi/SAPGlobal20/Global\">";
var soapre2 = "<soapenv:Header/><soapenv:Body><glob:EmployeeLeaveRequestByParticipantQuery><EmployeeLeaveRequestSelectionByParticipant><EmployeeLeaveRequestParticipantRoleCode listVersionID=\"?\">2</EmployeeLeaveRequestParticipantRoleCode>";
var soapre3 = "<!--Zero or more repetitions:--> <EmployeeLeaveRequestParticipantWorkAgreementIDInterval><IntervalBoundaryTypeCode>1</IntervalBoundaryTypeCode> <!--Optional:--> <LowerBoundaryWorkAgreementID schemeID=\"?\" schemeAgencyID=\"?\">1009</LowerBoundaryWorkAgreementID></EmployeeLeaveRequestParticipantWorkAgreementIDInterval>";
var soapre4 = " <!--Zero or more repetitions:--> </EmployeeLeaveRequestSelectionByParticipant></glob:EmployeeLeaveRequestByParticipantQuery> </soapenv:Body></soapenv:Envelope>";
var soapRequest = soapre1+soapre2+soapre3+soapre4;
var authstr = 'Basic ' +Titanium.Utils.base64encode('S0009231839'+':'+ 'm8390967743!');
var soapxhr = Ti.Network.createHTTPClient();
soapxhr.setRequestHeader('SOAPAction',soapRequest);
soapxhr.open("POST","http://erp.esworkplace.sap.com/sap/bc/srt/pm/sap/ecc_empleavereqparctqr/800/default_profile/2/binding_t_http_a_http_ecc_empleavereqparctqr_default_profile");
soapxhr.setRequestHeader('Authorization', authstr);
soapxhr.setRequestHeader('Content-Type','text/xml','charset=utf-8');
soapxhr.send();
soapxhr.onload = function(e)
{
Ti.API.info('abcd');
//get the xml data and let it roll!
var doc = this.responseXML;
Ti.API.info(doc);
}
soapxhr.onerror = function (e){
alert('Error');
Ti.API.info(e);
}
Unable to load the response Its directly getting error
[INFO] {
source = "[object TiNetworkClient]";
type = error;
}
Any one advice how to fix the issue!
# Thanks in advance
In all browser its saying error! but i found some wsdl and soap request so in order to open the response i need to pass the method name to the http request ! then it working

Categories