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?
Related
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.
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
Can you please let me know how I can get a ZIP file stored on same server using the jquery Ajax? Please be informed that I do not want to download the file
I need to pass the result , if success? to an API snippet like this, (this is using a Form to pass a zip file from client to the request Here is The Working Demo
request({
url: portalUrl + '/sharing/rest/content/features/generate',
content: myContent,
form: dom.byId('uploadForm'),
handleAs: 'json',
load: lang.hitch(this, function (response) {
if (response.error) {
errorHandler(response.error);
return;
}
var layerName = response.featureCollection.layers[0].layerDefinition.name;
addShapefileToMap(response.featureCollection);
}),
error: lang.hitch(this, errorHandler)
});
but I need to pass the zip file from server witout using a form and here is what I would like to do
var data = "www.mydomain.com/GIS/App.ZIP";
request({
....,
form: data,
....
});
Update
As menitoned API offers the Formdata option as well but how I can pass second parameter of type inside the append method?
var theFile = "http://localhost/Portal/APP.ZIP";
var myFormData = new FormData();
myFormData.append(theFile, ? );
Javascript cannot access the local filesystem without user intervention for security reasons. A user must take an action to load a file. Otherwise, it would be very easy for malicious web pages to traverse your file system.
You can use javascript via AJAX to trigger a server side script which can access the server file system and return results to javascript though.
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!!
Wherever I have the UI for uploading the document, I am easily able to use FormData api for uploading asynchronously to web api. Now I have a scenario where I need to upload a document based on file path without using UI or User Input so how can I do that?
Below is the code that I use when user uploads the file in form.
var formData = new FormData();
var myFile = $('#myFile')[0];
formData.append("myFile", myFile.files[0]);
$.ajax({
url: url,
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function (data, textStatus, xhr) {
console.log(data);
},
error: function (xhr, ajaxOptions, rtnError) {
alert(xhr.responseText + rtnError);
}
});
In general you cannot access to the client file system directly using JavaScript inside a browser (this is by design), and thus you will need the user to select the file manually to be able to upload it.
This question may further clarify what are the constraints in manipulating Files in JavaScript: Local file access with javascript