Sending a blob image via ajax using django - javascript

After a video is processed, I'm passed an instance of a Javascript "Blob" object, which contains the preview image (In JPEG format). I want to send the image via an ajax POST to the backend on django and am having trouble doing so.
I tried to encode to base64 in javascript, and then decode it in python and create the image again, but the image file can't be opened; it's either damaged or corrupt. I included the code that I wrote below:
Django:
def thumbnail_photo(request):
if request.POST:
data = request.POST.get('thumbnail')
convert = base64.b64decode(data)
image_result = open('thumbnail.jpeg', 'wb')
image_result.write(convert)
Javascript:
onPreviewAvailable: function(previewImageBlob) {
blob = previewImageBlob;
var reader = new window.FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function() {
base64data = reader.result;
base64 = base64data;
base64 = window.btoa(base64);
data = {'thumbnail': base64};
$.ajax({
url: 'thumbnail_photo',
type: 'POST',
data: data,
dataType:'json',
success: function (data) {
}
});
});
}
I also tried the following:
blob = previewImageBlob;
var oReq = new XMLHttpRequest();
oReq.open("POST", thumbnail_photo, true);
oReq.onload = function (
};
oReq.send(blob);
However, the value either came as empty or I would get an error saying that the file couldn't be sent.
I also tried appending the blob to form data:
var formData = new FormData();
formData.append('file', blob);
$.ajax({
url: 'thumbnail_photo',
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(response) {
console.log('works');
$('#result').text(response);
}
});
Any help is appreciated!!

Related

MediaStreamRecorder can't record more than an hour?

I am creating a video conference which takes 1 hour. And it can't save because Payload Too Large
Here is my code:
const data = [];
multiStreamRecorder.ondataavailable = function (blob) {
data.push(blob);
var fileName = getFileName('webm');
var scheduleId = $('#stop-recording').data('id');
var fileObject = new File([data[0]], fileName, {
type: data[0].type
});
var objectUrl = URL.createObjectURL(data[0]);
var formData = new FormData();
formData.append('video_blob', fileObject);
formData.append('video_filename', fileObject.name);
formData.append('schedule_id', scheduleId);
$.ajax({
url: '{{ url('/') }}/store',
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(response) {
//
}
});
};
multiMediaRecorder.start();
I need to record the entire conference.
The "payload too large" error comes from your server, not from the MediaRecorder API.
You probably have ways to raise that limit in your server's configs.
Alternatively, you could send the final file by chunks, but that's probably sub-optimal.
Unrelated note:
sending the blobURI is useless, this URI will only be valid for the context that did create it.

file uploading using javascript

This is my code to generate a zip file; I am unable to upload a .zip file to server, displaying error like [[Promise]] is not a file:
var zip = new JSZip();
zip.file("Hello.txt", "Hello World\n");
/*create a folder*/
var img = zip.folder("images");
/*create a file in images folder*/
img.file("Hello1.txt", "Hello111 World\n");
/* generate the zip file */
var content = zip.generateAsync({type:"blob"});
This is the code I tried to upload the zip file but got no response.
var fd = new FormData();
fd.append('fileZip', content);
$.ajax({
data: fd,
url: '/plan-upload/1',
type: 'POST',
processData: false,
contentType: false,
success: function(response) {
alert("success"); /*$('#text-us').modal('toggle');*/
}
});
Now, can we upload this generated zip file to server? If yes, how? If no, why?
When we generating the zip doing this code
var content = zip.generateAsync({type:"blob"});
In content variable has some object type date like promise or Blob type.
So backend code doesn't recognize it as a file,Now do this
var file = new File([content], "name.zip");
Now we can send this file, doing this
var fd = new FormData();
fd.append('fileZip', file);
$.ajax({
data: fd,
url: '/plan-upload/1',
type: 'POST',
processData: false,
contentType: false,
success: function(response) {
alert("success"); /*$('#text-us').modal('toggle');*/
}
});

Upload file with ajax and jquery.save image on server in C# code.

i want to create a fileupload with ajax and jquery.i send formData to server.i can not get data and save image on server.
it is my code in javascript:
function UploadFile() {
var fileName = $('#uploadFile').val().replace(/.*(\/|\\)/, '');
if (fileName != "") {
var formData = new FormData();
formData.append('file', $('input[type=file]')[0].files[0]);
$.ajax({
url: 'p1.aspx/uploadPic',
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function (dt) {
alert(dt.d);
}
});
}
}
code in p1.aspx page:
[WebMethod]
public static string uploadPic(HttpPostedFile file)
{
return file.FileName;
}
it is not work and not return any thing!what is wrong?how can get image on server?
best reagrds.

How to encrypt a binary file with HTML5 File API and upload to server

I need to encrypt and upload file to Apache/PHP server with HTML5 FileReader API and CryptoJS
I've done the following succesfully
Read file with FileReader API
Convert file to base64 with readAsDataURL() function
Encrypt it with the following
CryptoJS.AES.encrypt(e.target.result, password);
But I couldn't manage to send it to server as a File object because I already converted it to text object and I can't convert back it to a file. The following is my javascript file and server-side snippet.
app.js
var reader = new FileReader();
// Read file callback!
reader.onload = function (e) {
// Use the CryptoJS library and the AES cypher to encrypt the
// contents of the file, held in e.target.result, with the password
var encrypted = CryptoJS.AES.encrypt(e.target.result, password);
//SEND FORM DATA
var data = new FormData($("#fileinfo")[0]);
/*The following line doesn't work because I'm not adding a File object,
* I'm adding file already converted to Base64 format
*/
data.append('file-0','data:application/octet-stream,' + encrypted);
$.ajax({
url: 'upload.php',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function (data) {
//alert(data);
}
});
};
upload.php
<?php
var_dump($_FILES); //prints empty array
var_dump($_POST); //prints file as string
?>
I found the answer the new Draft on w3
Here is a working code if anyone need
var reader = new FileReader();
// Read file callback!
reader.onload = function (e) {
var encrypted = CryptoJS.AES.encrypt(e.target.result, password);
var data = new FormData($("#fileinfo")[0]);
var encryptedFile = new File([encrypted], file.name + '.encrypted', {type: "text/plain", lastModified: new Date()});
data.append('file[0]', encryptedFile);
$.ajax({
url: 'upload.php',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function (data) {
//alert(data);
}
});
};
reader.readAsDataURL(file);

How to upload a file using jQuery.ajax and FormData

When I use XMLHttpRequest, a file is correctly uploaded using FormData. However, when I switch to jQuery.ajax, my code breaks.
This is the working original code:
function uploadFile(blobFile, fileName) {
var fd = new FormData();
fd.append("fileToUpload", blobFile);
var xhr = new XMLHttpRequest();
xhr.open("POST", "upload.php", true);
xhr.send(fd);
}
Here is my unsuccessful jQuery.ajax attempt:
function uploadFile(blobFile, fileName) {
var fd = new FormData();
fd.append("fileToUpload", blobFile);
var xm = $.ajax({
url: "upload.php",
type: "POST",
data: fd,
});
}
What am I doing wrong? How can I get the file to be uploaded correctly, using AJAX?
You have to add processData:false,contentType:false to your method, so that jQuery does not alter the headers or data (which breaks your current code).
function uploadFile(blobFile, fileName) {
var fd = new FormData();
fd.append("fileToUpload", blobFile);
$.ajax({
url: "upload.php",
type: "POST",
data: fd,
processData: false,
contentType: false,
success: function(response) {
// .. do something
},
error: function(jqXHR, textStatus, errorMessage) {
console.log(errorMessage); // Optional
}
});
}
If you are uploading from a HTML5 form that includes an input fo type file you can just use querySelector and FormData and it works.
In case of php it will give you all files in the $_FILE and all other inputs in the $_POST array.
JS/jQuery:
function safeFormWithFile()
{
var fd = new FormData(document.querySelector('#myFormName'));
$.ajax({
url:'/catchFormData.php',
method:'POST',
data:fd,
processData: false,
contentType: false,
success:function(data){
console.log(data);
}
});
}
HTML:
<form id="myFormName">
<input id="myImage" name="myImage" type="file">
<input id="myCaption" name="myCaption" type="text">
</form>

Categories

Resources