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.
Related
I'm using a button click to trigger a file input dialog. Once the file is selected, I'm displaying the thumbnail in a preview.
const uploadListener = function() {
const preview = document.getElementById('preview')
const uploadBlob = window.URL.createObjectURL(this.files[0])
preview.style.backgroundImage = `url(${ uploadBlob })`;
}
const fileUploader = document.getElementById('fileUpload')
fileUploader.addEventListener('change', uploadListener)
From here, what's the easiest way to get the file at uploadBlob asynchronously sent (via XMLHttpRequest()?) to my node.js Express server and saved to the server?
I've written this out with a base64 encoded FileReader() in the past, where you have to filter out the metadata, then decode to a binary file and figure out the name + extension on the server, but it was slow and seemed sort of obscure.
It's misleading to name the variable uploadBlob since it's not a blob any more. it's a url, you don't send that to the server.
Basically, append the blob/file to a FormData, then send the formdata in your ajax request
const fd = new FormData()
fd.append('avatar', this.files[0])
// fd.append('avatar', this.files[0], optionalFileName)
fetch(uploadUrl, {method: 'post', body: fd})
/*
or using XMLHttpRequest:
var xhr = new XMLHttpRequest
xhr.open('POST', uploadURL)
xhr.send(fd)
*/
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
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.
I am using ajax jquery to send the image to the nodejs server. But I am stuck up at receiving the image in the nodejs server from the client.
Client code:
jQuery.noConflict();
formdata = new FormData();
jQuery("#afile").on("change", function() {
var file = this.files[0];
if (formdata) {
formdata.append("image", file);
jQuery.ajax({
url: "http://130.211.245.190:8080",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success:function(){}
});
}
});
Can anyone help me to receive the image in the server. Thanks in advance.
I think "this" should be wraped "$()"...
You could try it...
jQuery.noConflict();
formdata = new FormData();
jQuery("#afile").on("change", function() {
var file = $(this).files[0];
if (formdata) {
formdata.append("image", file);
jQuery.ajax({
url: "http://130.211.245.190:8080",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success:function(){}
});
}
});
To receive multipart/form-data in node you can use any of the following packages
busboy
multiparty
formidable
multer
If you are using express probably you are using body-parser but this package does not handle multipart/form-data due to their complexity.
This is a sample taken from the multer docs
var upload = multer({ dest: 'uploads/' });
app.post('/profile', upload.single('avatar'), function (req, res, next) {
// req.file is the `avatar` file
// req.body will hold the text fields, if there were any
})
You can lookup the req.file or the req.files for the uploaded files and their information like file name size and destination. Also req.body will contain any text fields if the request contains any.
If you are using plain node you can try the others to see if they fit your needs. They usually allow for more control but are more dificult to configure.
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?