Upload a javascript generated PDF file to server - javascript

Please note I am uploading a file generated at runtime, NOT a user submitted file. This is where my problem lies, taking that file and sending it along has proven itself to be truly a challenge.
I'm using PDFMake to generate a pdf file. It took me A LONG time to get this code working, tl;dr of it is I convert the pdf doc info to a buffer, make a new File object with that buffer, attach that file object to a formdata object, and send it to my server.
Here is the code:
var pdfGen = pdfMake.createPdf(docDef);
pdfGen.getBuffer(function(buffer){
var pdf = new File(buffer, "testpdf.pdf", {type: "application/pdf"});
var data = new FormData();
data.append('upload', pdf);
data.append('content-type', 'application/pdf');
$.ajax({
method: "POST",
url: "/index.cfm?action=admin:service.upload_pdf",
data: data,
processData: false,
contentType: false,
success: function(msg){
console.log(msg);
},
error: function(msg){
console.log(msg);
}
})
})
The problem is that the file I get on my server isn't a valid PDF. The application type is listed as application/octet-stream. The function I'm pushing the File object to SHOULD be rejecting everything except pdf's, so I'm not sure where the error is exactly.
I've been at this for two days now and I'm at a loss so any help is GREATLY appreciated.

Have you tried converting your generated PDF into Base64 and then sending the result to your server?
Here's what I mean:
var pdfGen = pdfMake.createPdf(docDef);
pdfGen.getBase64((data) => {
PostToServer(data);
});
Source: https://github.com/bpampuch/pdfmake

Related

Is it possible to read object from AJAX request on server side?

Actually, I'm trying to send video file in base64 but it the file is large (small files works fine) that's why ajax process not completed and I got 400 error.
So, I thought to send a file object like below so, I can read this object from the server-side. But I don't know if it is possible? OR is there any way through which I can handle large video file upload?
[object FileReader]
And here is my AJAX Code
var reader = new FileReader();
// this function is triggered once a call to readAsDataURL returns
reader.onload = async function(event){
var fileData = new FormData();
var fileType;
fileType = ".avi";
// console.log(my_script_vars.postID);
// fileData.append("file", event.target);
fileData.append("file", event.target.result);
fileData.append("action", "myaction");
fileData.append("filetype", fileType);
fileData.append("post_id", my_script_vars.postID);
jQuery.ajax({
url: 'https://www.reelme.app/sign-up/wp-admin/admin-ajax.php',
processData: false,
contentType: false,
cache: false,
data: fileData,
type: 'POST',
.......
.......
.......
});
}
Please help. Thanks in advance.
You shouldn't read the file into base64 and store everything in memory. screw that FileReader you have.
you are doing the right thing by using FormData, but a FormData can also append blob & files
// Simulate a file you would normally get from a file input or drag n drop
const file = new File(['abc'], 'sample.txt', { type: 'text/plain' })
const fd = new FormData()
fd.append('file', file)
then to upload it i would suggest that you use fetch instead of jQuery that requires all those processData & other config
const url = 'https://www.reelme.app/sign-up/wp-admin/admin-ajax.php'
fetch(url, { method: 'POST', body: fd })
.then(console.log, console.error)
JSON isn't meant to handle large binary data... b/c it's no good streaming format.

Writing UTF-8 to a file and downloading it with FileSaver.js

I've been working on making a Distributed File System and have come to a halt today with trying to write the contents of a returned file for the browser to download.
My system sends a request for a file's data and gets a string of the entire UTF-8 encoded binary contents as a response. I'm then trying to use FileSaver.js to write and download this content.
It only works for .txt files at the moment. I suspect it's something to do with the encoding and how the Blob object is made, I think it's simply writing the UTF-8 as text to each file which is why it works for .txt and nothing else. I've tried converting the response to byteArrays or using a File object instead but nothing works.
Here's the code doing the request and handling the response:
$.ajax({
type: "POST",
url: "http://localhost:3040/read",
data: {
data: data
},
xhrFields: {
withCredentials: true
},
success: function(response) {
var FileSaver = require('file-saver');
var blob = new Blob([response], {type: "application/octet-stream"});
FileSaver.saveAs(blob, filename);
}
});
An small snippet of the response output (in this case for a png image):
PNG
\u1a
\u0\u0\u1a
IHDR\u0\u0\u2î\u0\u0\u56Eµ¤Q\u0\u0\u0\u1sRGB\u0®Î\u1cé...

Upload Generated PDF with AJAX is Not Working or Timing Out

I am using JSPDF to dynamically generate a PDF with user information on my web app, which is built in React.js and hosted on Firebase.
On the final page, I would like to email this PDF to a list of addresses that the user specifies. This sounds straightforward, but I have encountered some issues. Firstly, I cannot send an email using just React.js. Doing some research has led me to create a request to a PHP file that uploads the file. In the PHP file, I then use the standard PHP mailer to send the emails.
JSPDF has these functions used to export the file:
var pdfInBase64 = doc.output('datauristring');
var pdfInRawFormat = doc.output();
Here are 2 of my attempts to solve this issue. Both use FormData.
var formData = new FormData();
formData.append("data", pdfInBase64); // also tried pdfInRawFormat
Using XMLHttpRequest:
var xhr = new XMLHttpRequest();
xhr.open('POST', 'uploader.php', true);
xhr.onload = function () {
if (xhr.status === 200) {
// File(s) uploaded.
console.log('completed');
} else {
alert('An error occurred!');
}
};
xhr.send(formData);
Using AJAX:
var $ = require ('jquery');
$.ajax({
type: "POST",
url: 'uploader.php',
data: formData,
dataType: 'json',
contentType: false,
processData: false
});
Both of the above methods don't seem to be working for me. When I go to my console and look at the "Networking" tab, I see that a request has been made, but it times out after 20+ seconds. I tried not uploading a file and just setting data as hello or any other string, and the PHP file successfully receives it. I'm thinking that the file that I have is too large, leading to a timeout.
Could someone please point me in the right direction on how to fix this? My end goal is to send an email with an attachment using JavaScript and PHP. Thanks!!

Send binary of file from ajax to ashx file as application/octet-stream

I need to send with ajax a file Binary to .ashx file (c# .net environment).
When I send it, the "Request Payload" must be of Content-Type: "application/octet-stream", this is the requirement from the server side. My problem is When I run my script, It sends the file as a normal type instead of "application/octet-stream". if the file is jpg, then it sends it as Content-type: "image/jpeg", This is not good for me. I wanna send the file in Binary format.
right now what I have is this:
var formData = new FormData();
formData.append('file',file);
$.ajax({
url: gatewayUrl,
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(data){},
error: function(){}
});
I read about FileReader, and about File.getAsBinary() but non of them is working for me. I am struggling with the ArrayBuffer and I'm not sure if I'm on the right direction..
This is the direction I'm thinking about but I can't figure out if that's the correct way to go with or not:
function get_file_binary(file){
var fileReader = new FileReader();
fileReader.readAsArrayBuffer(file);
fileReader.onload = function(e){
var res = fileReader.result;
var res2 = new Int8Array(res);
return res2;
}
}
But when I try this I get "undefined" at the "Request Payload" on chrome.

Reading in a file then creating a Blob of that file

If I want to read in a file (say: audio.mp3) and I know where it lives, and I want to recreate that file via javascript in a Blob so I can append it into FormData, is that possible?
$.ajax({
'type': 'GET',
'url': sounds/audio.mp3
}).done(function(body) {
var blob = new Blob([body], {'type': 'audio/mpeg'});
var formdata = new FormData();
//Set other things then...
data.append('audio.mp3', blob);
}).fail(function(jqXHR, textStatus) {
alert('failed');
});
It submits correctly to another web server that I need it to be sent to and I get a URL back to that file as re-created by the Blob, but I can no longer listen to the sound. Is this possible or am I just grasping at air?
Is it possible I am just forgetting to put something in to make the data structure correct for audio?

Categories

Resources