I can't send data to the server using AJAX - javascript

The situation is as follows: I upload a drag and drop image to the server. Everything would have been simpler, but first you need to embed the dropped image into the DOM tree, after which it can be removed from there, and the rest need to be sent to the server. At the drop event, I add the file itself and the picture className to the associative array. After the user is ready to send all the remaining pictures to the server, I add the files that have the classes of the remaining pictures as the key to the new array and form FormData of it. But the server does not receive files. Help!
code:
var arr = new Map;
//create a associative array.
dnd.addEventListener('drop', e => {
e.preventDefault();
var image_ = e.dataTransfer.files;
.....
//embed dropped image into the DOM tree
const text = e.dataTransfer.getData("text");
if (text) {
let img = document.createElement('img');
img.src = text;
$('#container_').append(img);
}
else {
const files = e.dataTransfer.files;
[].map.call(files, file => {
if (file.type.match(/^image/)) {
let reader = new FileReader();
reader.onload = file => {
let img = document.createElement('img');
img.className = "droppedPhoto" + Math.random();
img.setAttribute("widt", "200");
img.setAttribute("height", "200");
img.src = file.target.result;
let div = document.createElement('div');
$('#container_').append(div);
$('#container_').children().last().append(img);
arr.set(img.className, image_);
$('.sendPhotos > p > button').on('click', function () {
checkData(arr);
});
function checkData(array) {
var $arrOfImg = $('#container_ > div > img');
var $newArrayOfData =[];
for (var i = 0; i < $arrOfImg.length; i++) {
if (array.has($arrOfImg[i].className)) {
$newArrayOfData.push(array.get($arrOfImg[i].className));
}
}
createFormData($newArrayOfData);
}
function createFormData(images) {
var formImage = new FormData();
for (var i = 0; i < images.length; i++) {
formImage.append(key, images[i]);
}
uploadFormData(formImage);
}
function uploadFormData(formData) {
$.ajax({
url: '#Url.Action("PhotoSessionInfo", "Home")',
type: "POST",
xhr: function () {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
data: formData,
contentType: 'multipart/form-data',
cache: false,
processData: false,
success: function (response) {
console.log("success");
$('#container_').html(response);
}
});
}

Related

Is it possible to store base64 of a file in javascript object and send it to backend using ajax?

I am just trying to upload image file in base64 format by storing it in a js object. But the problem here is the object property 'baseData' doesn't fill with the DataURL of the image. If the way I mentioned below is possible, please suggest the solution to fill the 'baseData' property.
What I am doing is storing the 'type' (image or video, not extensions) and DataURL of the file in the object(fileDataObject) and pushing the object to an array(blobData), and returning the same at the end of the function.
Thanks in advance
var filesAccept = filesValidator($("#file-upload")[0].files);
if(filesAccept !== false){
var fd = new FormData();
fd.append("files", filesAccept)
$.ajax({
type: "POST",
url: "receiver.php",
data: fd,
processData: false,
contentType: false,
dataType: "text",
success: function (result) {
console.log(result);
},
});
}
function filesValidator(f) {
if (f.length === 0) {
$("#error-info").text("Please select some images or videos.");
return false;
} else if(f.length !== 0) {
var blobData = [];
var fileType;
$("#error-info").text("");
var n = 10;
if (f.length < 10) {// checking if files count less than 10
n = f.length;
}
for (let i = 0; i < n; i++) {
var reader = new FileReader();
fileType = f[i].type.split("/");
if(fileType[1] === "gif"){
return false;
} else if (fileType[0] === "image") {// if file is images
reader.onload = function(e) {
var src = e.target.result.split(",")[1];
console.log(src);
var fileDataObject = {
baseData : src,
type : "image"
};
blobData.push(JSON.stringify(fileDataObject));
}
reader.readAsDataURL(f[i]);
} else if(fileType[0] === "video") { //if file is video
reader.onload = function(e) {
var src = e.target.result.split(",")[1];
var fileDataObject = {
baseData : src,
type : "video"
};
blobData.push(JSON.stringify(fileDataObject));
}
reader.readAsDataURL(f[i]);
}
console.log(blobData);
}
return blobData;
}
}

Api from Asp core controller not receive all the value that FormData.append(key,value) appended

I want to upload files(image, setup file) and some other text string together.
This is my ajax code:
function uploadFiles(inputId) {
var input = document.getElementById(inputId);
var files = input.files;
formData = new FormData();
for (var i = 0; i !== files.length; i++) {
var temp1 = files[i];
}
formData.append('temp', 1);
formData.append('temp', "ksjhdfksdjf");
$.ajax({
type: "POST",
url: "/Admin/FileUploadView/SaveEntity",
data: formData,
contentType: false,
processData: false,
beforeSend: function () {
tedu.startLoading();
},
success: function () {
},
error: function () {
}
});
}
This is my controller:
When I log all the files that formData object contain, everything is ok:
But I only receive 2 image's objects in the controller:
Now I want that I can receive all the files that I appended. Do you have any ideas, please help me.
You do not receive your temp in your controller.
js:
function uploadFiles(inputId) {
var input = document.getElementById(inputId);
var files = input.files;
var formData = new FormData();
for (var i = 0; i != files.length; i++) {
formData.append("files", files[i]);
}
formData.append('temp', 1);
formData.append('temp', "ksjhdfksdjf");
//ajax
controller:
[HttpPost]
public async Task<IActionResult> SaveEntity(IList<IFormFile> files,List<string> temp)

Javascript: How to encrypt a zip file with RSA

I'm using Cryptico to handle RSA encryption for chat but I'm running into trouble trying to encrypt a zip file after construction. I see the constructed file in the console. The console shows an encrypted string of the file but returns blank after decryption in the console.
Note: my decryption method works properly with text and base64
$(document).on("change", "#chatImage", function() {
var rid = $(this).closest(".chat").data("id");
var files = this.files;
var zip = new JSZip();
for (var i = 0; i < files.length; i += 1) {
var file = files[i];
zip.file(file.name, file);
console.log("added", file.name);
// console.log(file);
}
var eImgArray = {};
$.ajax({
url : ajax_object.ajax_url,
type : 'post',
data : {
action: 'get_room_member_keys',
rid : rid,
},
beforeSend: function() {
},
success: function(html) {
var pubKeys = $.parseJSON(html);
$.each( pubKeys, function( key, value ) {
var imgEncrypt = cryptico.encrypt(file, value);
var imgSrc = imgEncrypt.cipher;
eImgArray[key] = imgSrc;
});
var strImgArray = JSON.stringify(eImgArray);
$("#chatFormCont input[name=image_data]").val(strImgArray);
var foo = $("#chatFormCont input[name=image_data]").val();
// console.log(foo);
},
});
zip.generateAsync({type: "blob"}).then(function(content) {
function show_all_images(relpath, file) {
if (file.dir) {
return file.forEach(show_all_images);
}
var img = $("#chatImagePreview");
file.async("blob").then(function(blob) {
var src = window.URL.createObjectURL(blob);
img.attr("src", src);
});
}
new JSZip.loadAsync(content).then(zip => zip.forEach(show_all_images));
});
});

Progress Bar in ajax while uploading 2 files or more

Hi Im trying to upload a 2 file or more, my problem is my progress bar will say 100% because of the small file being uploaded first, then its going back to the percent of the large file.. My question is how can I have a same progress if i have many files being uploaded?
$('body').on('change', 'input:file.gallery_images', function(event)
{
event.preventDefault();
var data = new FormData();
data.append('id', $("#id").val());
var count = $(this)[0].files.length;
$.each($(this)[0].files, function(i, file)
{
data.append('userfile', file);
$.ajax(
{
type: "POST",
url: href+path+"/imagens/store",
data: data,
mimeType: 'multipart/form-data',
contentType: false,
cache: false,
processData: false,
dataType: "json",
xhr: function()
{
var _xhr = $.ajaxSettings.xhr();
_xhr.addEventListener('progress', function (event) { }, false);
if (_xhr.upload)
{
_xhr.upload.onprogress = function(event)
{
var percent = 0;
if (event.lengthComputable)
{
var position = event.position || event.loaded;
var total = event.totalSize || event.total;
percent = Math.ceil(position / total * 100);
}
$("#progress-bar").width(percent + '%');
};
}
return _xhr;
},
beforeSend: function()
{
$("#progress").fadeIn('slow');
$("#progress-bar").width('0%');
},
success: function(data)
{
if(data.gallery)
{
if($(".alert").length > 0)
{
$(".alert").hide('slow').remove();
$("#droppable").show('slow');
}
$('.gallery').fadeTo('300', '0.5', function () {
$(this).html($(this).html() + data.gallery).fadeTo('300', '1');
});
}
$("#progress").fadeOut('slow');
}
});
});
});
Ok, first thing I noticed is that you're adding the file to the 'data' variable inside your $.each... but that means the first POST contains the first image, the second POST contains the first and the second, and so on. I think you should this part inside your $.each:
var data = new FormData();
data.append('id', $("#id").val());
Ok, so, to solve your problem: Before sending anything, go through them and sum their size. You'll also need to store the progress for each file individually, so start it as zero:
var sumTotal = 0;
var loaded = [];
for (var i = 0, list = $(this)[0].files; i < list.length; i++) {
sumTotal += list[i].size;
loaded[i] = 0;
}
Inside your onprogress, instead of comparing the event.position with the event.totalSize, you'll store this position on your 'loaded' array, sum all your array, and then compare it to your sumTotal.
loaded[i] = event.position || event.loaded;
var sumLoaded = 0;
for (var j = 0; j < loaded.length; j++) sumLoaded += loaded[j];
percent = Math.ceil(sumLoaded * 100/sumTotal);
;)

How to add Croppie result to upload php and pass the result to other php page

I am trying to develop a app which fetches image from facebook sdk or via ajax upload and crop using croppie.js and upload to my server directory. I am new to Ajax,jQuery and php. I found a similar app in internet which performs same functions I thought .Here is code of that app.js
function dataURItoBlob(dataURI) {
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0) byteString = atob(dataURI.split(',')[1]);
else byteString = unescape(dataURI.split(',')[1]);
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {
type: mimeString
});
}
window.uploadPicture = function(callback) {
croppie.result({
size: "viewport"
}).then(function(dataURI) {
var formData = new FormData();
formData.append("design", $("#fg").data("design"));
formData.append("image", dataURItoBlob(dataURI));
$.ajax({
url: "upload.php",
data: formData,
type: "POST",
contentType: false,
processData: false,
success: callback,
error: function() {
document.getElementById("download").innerHTML = "Download Profile Picture";
},
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
myXhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
var max = e.total;
var current = e.loaded;
var percentage = Math.round((current * 100) / max);
document.getElementById("download").innerHTML = "Uploading... Please Wait... " + percentage + "%";
}
}, false);
}
return myXhr;
},
});
});
}
window.updatePreview = function(url) {
document.getElementById("crop-area").innerHTML = "";
window.croppie = new Croppie(document.getElementById("crop-area"), {
"url": url,
boundary: {
height: 400,
width: 400
},
viewport: {
width: 400,
height: 400
},
});
$("#fg").on('mouseover touchstart', function() {
document.getElementById("fg").style.zIndex = -1;
});
$(".cr-boundary").on('mouseleave touchend', function() {
document.getElementById("fg").style.zIndex = 10;
});
document.getElementById("download").onclick = function() {
this.innerHTML = "Uploading... Please wait...";
uploadPicture(function(r) {
document.getElementById("download").innerHTML = "Uploaded";
window.location = "download.php?i=" + r;
});
};
document.getElementById("download").removeAttribute("disabled");
};
window.onFileChange = function(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
image = new Image();
image.onload = function() {
var width = this.width;
var height = this.height;
if (width >= 400 && height >= 400) updatePreview(e.target.result);
else alert("Image should be atleast have 400px width and 400px height");
};
image.src = e.target.result;
}
reader.readAsDataURL(input.files[0]);
}
}
$(document).ready(function() {
$(".design").on("click", function() {
$("#fg").attr("src", $(this).attr("src")).data("design", $(this).data("design"));
$(".design.active").removeClass("active");
$(this).addClass("active");
});
});
I have created a frontend with this code. But i can't go further.I need upload.php code which uploads to my server and send the output to download.php where I can add share buttons to share cropped iamge. Please do needfull and share possible upload.php code and download.php code that works with this javascript. Thanks a lot!
I can't help you with php but I have just a few suggestions to your code
You can return a blob directly from croppie so you don't need to build it yourself
croppie.result({
size: 'viewport',
type: 'blob'
}).then(function(blob) {
...
formData.append('image', blob, 'screenshot.png')
...
})
and on your onFileChange function you don't have to use the FileReader, you can just use the
image.src = URL.createObjectURL(input.files[0])

Categories