file uploading using javascript - 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');*/
}
});

Related

Google Drive API multipart upload gets file corrupted, size 1kb

I've been trying to upload a file using the Google Drive API but I'm facing this issue and I can't seem to find the solution. When uploading an image, it uploads a corrupted file of size 1kb with correct metadata and while uploading text files, it uploads a text file with [object file] as data and not the original data of the file.
$("form").submit(function(evt){
evt.preventDefault();
var formData = new FormData($(this)[0]);
var control = document.getElementById("csv");
var files = control.files;
var dat=files[0];
$.ajax({
url: 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart',
type: 'POST',
contentType: false,
data: "\n--foo_bar_baz\ \nContent-Type: application/json; charset=UTF-8\ \n\n{ 'name': '"+dat.name+"' }\ \n--foo_bar_baz\ \nContent-Type: "+dat.type+"\ \nContent-Transfer-Encoding: base64\ \n\n"+dat+"\ \n--foo_bar_baz--\ ",
headers: {
"Authorization":"Bearer <?php echo $result["access_token"]; ?>",
"Content-Type": "multipart/related; boundary=foo_bar_baz",
"Content-Length": formData.length
},
async: false,
cache: false,
enctype: 'multipart/form-data',
processData: false,
success: function (response) {
var res = JSON.stringify(response);
console.log("S: "+res);
},
error: function(response) {
var res = JSON.stringify(response);
console.log("E: "+res);
}
});
return false;
});
How about this answer? Please think of this as just one of several possible answers.
Modification points:
You are trying to upload the file as base64. But in your script, dat is not base64.
In this case, I used FileReader.
Please remove \ of \ \n in "\n--foo_bar_baz\ \nContent-Type: application/json; charset=UTF-8\ \n\n{ 'name': '"+dat.name+"' }\ \n--foo_bar_baz\ \nContent-Type: "+dat.type+"\ \nContent-Transfer-Encoding: base64\ \n\n"+dat+"\ \n--foo_bar_baz--\ ",.
When above points are reflected to your script, it becomes as follows.
Modified script:
$("form").submit(function(evt){
evt.preventDefault();
var formData = new FormData($(this)[0]);
var control = document.getElementById("csv");
var files = control.files;
var dat = files[0];
var f = new FileReader(); // Added
f.onload = function(){ // Added
const base64Data = this.result.split(",")[1]; // Added
$.ajax({
url: 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart',
type: 'POST',
contentType: false,
data: "\n--foo_bar_baz\nContent-Type: application/json; charset=UTF-8\n\n{'name': '"+dat.name+"'}\n--foo_bar_baz\nContent-Type: "+dat.type+"\nContent-Transfer-Encoding: base64\n\n"+base64Data+"\n--foo_bar_baz--\n", // Modified
headers: {
"Authorization": "Bearer <?php echo $result["access_token"]; ?>",
"Content-Type": "multipart/related; boundary=foo_bar_baz",
"Content-Length": formData.length
},
async: false,
cache: false,
enctype: 'multipart/form-data',
processData: false,
success: function (response) {
var res = JSON.stringify(response);
console.log("S: "+res);
},
error: function(response) {
var res = JSON.stringify(response);
console.log("E: "+res);
}
});
}
f.readAsDataURL(dat); // Added
return false;
});
Note:
When uploadType=multipart is used, the maximum file size is 5 MB. Please be careful this. Ref
If this was not the direct solution of your issue, I apologize.

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.

Sending a blob image via ajax using django

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!!

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