Ajax post has previous data - javascript

This is driving me crazy. I know I am doing something wrong but what? The problem is I am getting previous data in my ajax call when I post it to php.
Story: I click upload button which calls JavaScript loadme() where i am cleaning the input type file element. I then select file/files and click upload which calls doit() which internally calls uploadFiles(). UploadFiles makes an array with loaded images and post it to the php file through ajax.
I have tried plain javascript and jquery to clean file input element and php to set post values to null after using it, but still i am getting the previous values.
The form
<form id="theform" method="post" action="" enctype="multipart/form-data" target="multifile">
<input type="hidden" id="folderpath" name="folderpath" value="<?=htmlspecialchars($path)?>">
<input name="upfiles[]" id="upfiles" type="file" multiple="" />
</form>
Javascript
async function doit(){
//some code
uploadFiles();
}
function loadmeup(){
$('upfiles').value = '';
$('uploadbox').show();
}
function closeupload(){
$('uploadbox').hide();
}
var masterFileArray = [];
var left_loaded_count = 0;
var progress = 0;
function uploadFiles() {
var files = document.getElementById("upfiles").files;
var path = document.getElementById('folderpath').value;
var numOfFiles = files.length;
alert(numOfFiles);
if (files && numOfFiles>0) {
for (var i = 0, f; f = files[i]; i++) {
if(checkExtension(f.name) && checkSize(f.size)){
progress = i+1/numOfFiles;
var r = new FileReader();
r.onload = (function (f) {
return function (e) {
var contents = e.target.result;
masterFileArray.push({name:f.name, contents: contents, type:f.type, size:f.size});
console.log(f.name);
left_loaded_count -= 1;
if(left_loaded_count == 0)
{
var filesarray = null;
filesarray = JSON.stringify(masterFileArray);
console.log("after stringify: "+filesarray.length);
new Ajax.Request('upload_do.php', {
method: 'post',
parameters: {files: filesarray, folderpath:path},
onSuccess: function(transport){
var response = transport.responseText;
parent.notify(response);
closeupload();
get_listview(currlist,sort);
}
});
}
};
})(f);
left_loaded_count += 1;
r.readAsDataURL(f);
}
else{
alert('Invalid file extension or size ' + f.name);
if(progress==0)
location.reload();
}
}
} else {
alert('Failed to load files');
closeupload();
}
}
PHP
try{
$error = null;
$files = json_decode($_POST['files'],true);
$numFiles = 0;
foreach($files as $file){
$output = $reso->writeUpload($file['contents'], $file['name']);
$numFiles++;
}
}
catch (Exception $ex){
$error = $ex->getMessage();
$GLOBALS['log']->log($error);
}
isset($_POST['files'])? $_POST['files'] = null: '';
if (!is_null($error))
echo _($error);
else
echo _($numFiles.' file'.(($numFiles > 1) ? 's' : '').' successfully
uploaded');

Related

how to specify which files should be uploaded onn file upload using javascript or jquery

I am uploading files onto a folder within my application using the code below. I would like to know how I can specify which type of files can be uploaded into that folder in my case I only want the user to be able to upload xls,xlxs and csv files. The user should not be allowed to upload docx or images etc
function OnUpload(evt) {
var files = $("#fileUpload").get(0).files;
if (files.length > 0) {
ShowUploadProgress();
if (window.FormData !== undefined) {
var data = new FormData();
for (i = 0; i < files.length; i++) {
data.append("file" + i, files[i]);
}
$.ajax({
type: "POST",
//url: "/api/ExcelBulkUpload",
url: "/api/FileUpload",
contentType: false,
processData: false,
data: data,
success: function (results) {
ShowUploadControls();
$("#uploadResults").empty();
for (i = 0; i < results.length; i++) {
$("#uploadResults").append($("<li/>").text(results[i]));
}
///"location.href='<%: Url.Action("Upload", "Controller") %>'"
window.location.href = '#Url.Action("UploadPage", "Home")';
},
error: function (xhr, ajaxOptions, thrownError) {
ShowUploadControls();
alert(xhr.responseText);
}
});
} else {
alert("Your browser doesn't support HTML5 multiple file uploads! Please use another browser.");
}
}
}
What I have researched so far
_validFileExtensions = [".xls", ".xlsx"];
var sFileName = oInput.value;
if (sFileName.length > 0) {
var blnValid = false;
for (var j = 0; j < _validFileExtensions.length; j++) {
var sCurExtension = _validFileExtensions[j];
if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
blnValid = true;
//$('#fileinput').val('');
break;
}
You can check file extension, and based on that if file extension are allowed then call upload function, else display message that selected file not allowed to upload.
Se below example.
Note : Only client side validation is not enough, also put validation on server side.
$(document).on("change","#myfile", function (e) {
var _theFormFile = $('#myfile')[0].files[0];
var ext = getExt(_theFormFile.name);
if(ext == ".xls" || ext == ".xlxs " || ext == ".csv") {
alert('call upload file function');
} else {
alert('display false message')
return false;
}
});
function getExt(filename) {
var ext = filename.split(".");
var cnt = ext.length;
ext = ext[cnt - 1];
ext = "." + ext.toLowerCase();
return ext;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='file' name="myfile" id="myfile">
First you can select what file types the users can input by default with
<input accept=".fileType" />
And then check the filetyp if they changed the filter
function upload(){
var fileName = document.getElementById("file").files[0].name;
console.log(fileName.substr(fileName.lastIndexOf(".")));
}
<input id="file" type="file" accept=".xls,.xlxs,.csv" />
<button onClick="upload()">send</button>

Ajax data not being displayed after upload

Currently my entire code is working almost flawlessly, how ever upon upload the ajax data is not being displayed on my webpage after a successful upload.
Below is the code I am using (completely) because I am rather new and have been reviewing various stack over flow posts to guide me in building this.
Sorry for lack of structure below.. I don't know how to adapt to stack overflows structure requirements..
The actual form input / submit
<form action="upload2.php" class="upload" enctype="multipart/form-data" id="upload" method="post" name="upload">
<fieldset>
<legend>Uplaod Files</legend> <input id="file" multiple name="file[]" required="" type="file"> <input id="submit" name="submit" type="submit" value="upload">
</fieldset>
<div class="bar">
<span class="bar-fill" id="pb"><span class="bar-fill-text" id="pt"></span></span>
</div>
<div class="uploads" id="uploads"></div>
</form>
Here's the PHP code I am using to upload the file.
<?
header('Content-Type: application/json');
$upload = [];
$allowed = ['mp3', 'm4a'];
$succeeded = [];
$failed = [];
if (!empty($_FILES['file'])) {
foreach ($_FILES['file']['name'] as $key => $name) {
if ($_FILES['file']['error'][$key] === 0) {
$temp = $_FILES['file']['tmp_name'][$key];
$file_name = $_FILES['file']['name'][$key];
$file_size = $_FILES['file']['size'][$key];
$ext = explode('.', $name);
$ext = strtolower(end($ext));
$s = substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", 4)), 0, 4);
$file = $s . '.' . $ext;
$data = $file_name . PHP_EOL . $file_size;
file_put_contents('d/' . $s . '.txt', $data);
if (in_array($ext, $allowed) === true && move_uploaded_file($temp, "v/{$file}") === true) {
$succeeded[] = array(
'name' => $name,
'file' => $file,
);
} else {
$failed[] = array(
'name' => $name
);
}
}
}
if (isset($_POST['ajax'])) {
echo json_encode(array(
'succeeded' => $succeeded,
'failed' => $failed
));
}
}
Below is javascript event listener + the returned data from ajax
document.getElementById('submit').addEventListener('click', function (e) {
e.preventDefault();
var f = document.getElementById('file'),
pb = document.getElementById('pb'),
pt = document.getElementById('pt');
app.uploader({
files: f,
progressBar: pb,
progressText: pt,
processor: 'upload2.php',
finished: function (data) {
var uploads = document.getElementById('uploads'),
succeeded = document.createElement('div'),
failed = document.createElement('div'),
anchor,
span,
x;
if (data.failed.length) {
failed.innerHTML = '<p>file didnt upload<\/p>';
}
uploads.innerText = '';
for (x = 0; x < data.succeeded.length; x = x + 1) {
anchor = document.createElement('a');
anchor.href = 'uploads/' + data.succeeded[x].file;
anchor.innerText = data.succeeded[x].name;
archor.target = '_blank';
console.log(anchor);
succeeded.appendChild(anchor);
}
uploads.appendChild(succeeded);
},
});
});
Below is the javascript we're using for ajax (I think the issue is here but I keep reviewing it and I'm not able to find the problem.)
var app = app || {};
(function (o) {
"use strict";
var ajax, getFormData, setProgress;
ajax = function (data) {
var xmlhttp = new XMLHttpRequest(),
uploaded;
xmlhttp.addEventListener('readystatechange', function () {
if (this.readystate === 4) {
if (this.status === 200) {
uploaded = JSON.parse(this.response);
if (typeof o.options.finished === 'function') {
o.options.finished(uploaded);
}
} else {
if (typeof o.options.error === 'function') {
o.options.error();
}
}
}
});
xmlhttp.upload.addEventListener('progress', function (event) {
var percent;
if (event.lengthComputable === true) {
percent = Math.round((event.loaded / event.total) * 100);
setProgress(percent);
}
});
xmlhttp.open('post', o.options.processor);
xmlhttp.send(data);
};
getFormData = function (source) {
var data = new FormData(),
i;
for (i = 0; i < source.length; i = i + 1) {
data.append('file[]', source[i]);
}
data.append('ajax', true);
return data;
};
setProgress = function (value) {
if (o.options.progressBar !== undefined) {
o.options.progressBar.style.width = value ? value + '%' : 0;
}
if (o.options.progressText !== undefined) {
o.options.progressText.innerText = value ? value + '%' : '';
}
};
o.uploader = function (options) {
o.options = options;
if (o.options.files !== undefined) {
ajax({});
ajax(getFormData(o.options.files.files));
}
}
}(app));
My file is uploading, the progress bar is working and without returning e.preventDefault(); when it redirect to upload2.php I'm able to see the contents of the json i really don't know what my problem could be..
First of all, you have a typo in anchor here:
archor.target = '_blank';
Maybe this throws error and stops other code execution
Also you could check if your uploads div is visible via element inspector in browser.
If console.log shows nothing - do you mean by this it is not even called or it shows undefined? If it doesn't show at all, then look into the for that uses data.succeeded.length param as a limit - maybe it equals 0 and thus console.log is never called

Splice, Upload, and Re-Combine File Blobs

I am currently working on an upload system with a combination of Javascript and PHP. The Javascript essentially reads a file in by splicing blobs of cutoffSize size (or, the remaining file size, if less). Each splice is sent to the php script via Post. Then, the PHP script re-assembles the file blob by blob.
However, in my implementation (as shown below), the output file is too large. I am not sure why the file is not being written correctly, but I believe that I have localized the problem to the php script. All of my javascript testing appears to have succeeded. However, I have included the Javascript as well, just in case.
I believe the problem may be in the way I write/append files. Unfortunately, I am not sure how to move forward, so I cannot investigate this further or describe in more detail.
Any help would be greatly appreciated.
Javascript:
function getBigStringAndPost(files,i,p) {
var key = $("#keyText")[0].value
var reader = new FileReader();
var blob = files[i].slice(p*cutoffSize,Math.min((p+1)*cutoffSize,files[i].size));
var folderName = $("#folderInput")[0].value;
reader.onload = function(e) {
var result = reader.result;
console.log(result.length);
$.post("http://brandonquinndixon.com/PHP/uploadFile.php",{
uploadKey: key,
doUpload: 1,
folderName: folderName,
splitPart: p,
fileName: files[i].name,
fileContents: reader.result
},function(e) {
console.log(e);
if ((p+1)*cutoffSize<files[i].size) {
currentUploaded += cutoffSize;
updateProgressBar();
reader.abort();
getBigStringAndPost(files,i,p+1);
} else {
$("#statusDiv").html($("#statusDiv").html()+"<p class='normalP'>File: "+files[i].name+" uploaded successfully.</p>");
currentUploaded += files[i].size%cutoffSize;
updateProgressBar();
reader.abort();
loadNextFile(files,i+1);
}
});
};
reader.onerror = function(e) {
console.log(e);
totalSizeOfFiles -= files[i].size;
$("#statusDiv").html($("#statusDiv").html()+"<p class='normalP'>File: "+files[i].name+" could not be read.</p>");
loadNextFile(files,i+1);
};
reader.readAsBinaryString(blob);
}
PHP:
$targetDir = $_SERVER['DOCUMENT_ROOT']."/Downloads";
$getKey = $_POST['uploadKey'];
$data = array();
error_log("upload attempt started");
//first, check the upload key
if ($getKey !== $uploadKey) {
$data['status'] = "failure";
$data['message'] = "Incorrect Upload Key";
error_log("bad key");
} else if ($_POST['doUpload'] == 1) {
$fileName = "";
if ($_POST['folderName']!=="") {
$folderName = cleanInput($_POST['folderName']);
if (!is_dir($targetDir."/".$folderName)) {
mkdir($targetDir."/".$folderName, 0777, true);
}
$fileName = $targetDir."/".$folderName."/".$_POST['fileName'];
} else {
$fileName = $targetDir."/".$_POST['fileName'];
}
/*
Don't allow executables
*/
if (strpos($fileName,".exe") > -1 || strpos($fileName,".sh") > -1 || strpos($fileName,".deb") > -1 || strpos($fileName,".rpm") > -1) {
$data['status'] = 'failure';
$data['message'] = 'Executable type files are not allowed';
} else {
if ($_POST['splitPart'] == 0) {
overWriteFile($fileName,$_POST['fileContents']);
$data['type'] = 'overWrite';
$data['details'] = 'P '.$_POST['splitPart'];
} else {
appendFile($fileName,$_POST['fileContents']);
$data['type'] = 'append';
$data['details'] = 'P '.$_POST['splitPart'];
}
$data['status'] = 'success';
}
} else {
$data['status'] = 'success';
$data['type'] = 'none';
error_log("success, no upload");
}
echo json_encode(array($data));
function overWriteFile($fName,$fContents) {
$fName = lookupFile($fName);
$file = fopen($fName,"w");
fwrite($file,$fContents);
fclose($file);
}
/*
Append to end of file
*/
function appendFile($fName,$fContents) {
$fName = lookupFile($fName);
//$file = fopen($fName,"a");
//fwrite($file,$fContents);
//fclose($file);
file_put_contents($fName,$fContents,FILE_APPEND);
}

How do I upload file on an aspx page without using webforms?

I have an aspx page which already has a code for uploading file using "asp:FileUpload" and webform. On a different section of page, I want to add the functionality for a user to upload file. But i do not want to use webforms or "asp:fileupload".
So, I created an HTML file that i inject as an iframe inside a div tag on the aspx.
<div id="iUploadDoc" style="height:50px;">
<iframe name='FileUpload' id='FileUpload' class='iUploadFrame' width='100%' frameborder='0' border='0'src='DocUpload.htm'></iframe></div>
I set the EnablePageMethods to true.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
And inside the HTML I made a form and with input type file.
<form method="POST" action="DocDetail.aspx.cs" id="docUpload" enctype="multipart/form-data">
<div>
<label for="fileUpload" class="inputLabel">Upload File</label>
<input type="file" id="fileUpload" name="files"/>
</div>
</form>
<div id="progUpload" style="display: none;">
<p class="uploadBox">Uploading...</p>
</div>
<span id= "selectedFile" style="display: none;"></span><span id="fileName" style="display: none;"></span>
Now, I dont know what to put in the "action" param of form.
First on the iframe, below is the script i wrote:
window.onload = load;
function uploadDocFile() {
var prog = document.getElementById("progUpload");
prog.style.cssText = 'display: block;';
var x = document.getElementById("fileUpload");
var txt = "";
var filePath = "";
var fileName = "";
if (x.value == "") {
txt += "Select a file.";
document.getElementById("selectedFile").innerHTML = txt;
} else {
filePath = x.value;
fileName = filePath.replace(/^.*[\\\/]/, '');
txt += "<br>Selected file: ";
document.getElementById("selectedFile").innerHTML = txt;
document.getElementById("fileName").innerHTML = fileName;
}
var formInfo = document.getElementById("docUpload");
document.getElementById("docUpload").style.display = "none";
window.parent.getFormData(formInfo, x ,x.value, fileName);
}
function load() {
var e = document.getElementById("fileUpload");
//var formInfo = document.getElementById("docUpload");
//fakeClick();
e.onchange = function () {
uploadDocFile();
}
}
Then on the parent page, below is the script i wrote.
DocUpload.prototype.uploadFileDoc= function (formInfo, uploadedFile, fileInfo, lastModifiedDate, name, extension, size, type) {
//blacklitsType is an array of types of file (similarly for blacklistExt) that should not be allowed to upload
if (indexOf.call(blackListType, type) < 0 && indexOf.call(blackListExt, extension) < 0) {
var idParams = { OiD: ordId, pID: pId, QID: qId }
var files = uploadedFile.files;
var fileEntries = [];
for (j = 0, len1 = files.length; j < len1; j++) {
file = files[j];
if (file.getAsEntry) {
entry = file.getAsEntry();
} else if (file.webkitGetAsEntry) {
entry = file.webkitGetAsEntry();
}
if (entry) {
isFyl = entry.isFile;
if (!isFyl) {
alert("You can not upload a folder. Uploading files (if present).");
} else {
fileItem = file.getAsFile();
fileEntries.push(fileItem);
}
} else if (!file.type && file.size % 4096 === 0) {
alert("You can not upload a folder. Uploading files (if present).");
} else {
fileEntries.push(file);
}
}
PageMethods.UploadDocument(fileEntries[0], idParams, function (res) {
if (res == true) {
alert("File uploaded successfully.");
} else {
alert("File upload failed.");
}
}, function (err) {
alert("ERROR: " + err._message);
});
} else {
window.alert('You cannot upload incorrect file types.');
}
return;
};
DocUpload.prototype.getFormData = function (formInfo, uploadedFile, fileInfo, nameInfo) {
var currDate, extension, lastModifiedDate, name, nameArr, size, type;
currDate = new Date();
lastModifiedDate = currDate;
type = '';
size = 512;
name = nameInfo;
nameArr = name.split(".");
extension = nameArr[nameArr.length - 1];
DocUpload.prototype.uploadFileDoc(formInfo, uploadedFile, fileInfo, lastModifiedDate, name, extension, size, type);
};
window.getFormData = DocUpload.prototype.getFormData;
The transfer of attributes of form from iframe to parent page work just fine. But how should i post it as file using PageMethod. Below is the page method in my code behind:
[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = false)]
public static bool UploadDocument(HttpPostedFileBase uploadedFile,IdParams idParams) {
bool err = false;
try{
//code
err= true;}
catch(Exception ex){err = false;}
return err;
}
No matter how much tried, either I keep getting error regarding HTTPPostedFileBase or Serialization of child not allowed.Below are only some of the errors i keep getting (not at the same time):
No parameterless constructor System.Web.HttpPostedFileBase aspx, OR
The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter
What should i do?

how to put double variable data in ajax

i've case to use variable more the one like code bellow :
function upload(iddata,ring)
{
//variable 1
dataString ="iddata="+iddata+"&ring="+ring+""; // variable 1
//variable 2
var formData = new FormData();
for (var i = 0; i < filesToUpload.length; i++) {
var file = filesToUpload[i];
formData.append("file[]", file, file.name);
}
// i want put both variabel in ajax like this
$.ajax({
data: {formData,dataString}, //variable 1 and 2 in group
});
}
please how source is True
You should handle your whole data as an object only, and not mix it as a string and a array in a object. In this case you would not get the expected data in your receiver.
You could change it like this:
function upload(iddata, ring) {
var data = {
iddata: iddata,
ring: ring,
formData: new FormData()
};
for (var i = 0; i < filesToUpload.length; i++) {
var file = filesToUpload[i];
data.formData.append("file[]", file, file.name);
}
$.ajax({
data: data
});
}
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class MyBird extends CI_Controller {
/**
* Index Page for this controller.
function add_bird()
{
// get user id posted
$iddata=empty($_POST['iddata']) ? '' : $_POST['iddata'];
$ring=empty($_POST['ring']) ? '' : $_POST['ring'];
//echo json_encode(array('uploaded' => 'Oke Bos'));
if ( ! empty($_FILES))
{
$config['upload_path'] = "./assets/images/uploads";
$config['allowed_types'] = 'gif|jpg|png|mp4|ogv|zip';
$this->load->library('upload');
$files = $_FILES;
$number_of_files = count($_FILES['file']['name']);
$errors = 0;
// codeigniter upload just support one file
// to upload. so we need a litte trick
for ($i = 0; $i < $number_of_files; $i++)
{
$Random_Number = rand(0, 9999999999); //Random number to be added to name.
$NewFileName = "Ring".$ring._.$Random_Number; //new file name
$config['file_name'] = $NewFileName;
$_FILES['file']['name'] = $files['file']['name'][$i];
$_FILES['file']['type'] = $files['file']['type'][$i];
$_FILES['file']['tmp_name'] = $files['file']['tmp_name'][$i];
$_FILES['file']['error'] = $files['file']['error'][$i];
$_FILES['file']['size'] = $files['file']['size'][$i];
// we have to initialize before upload
$this->upload->initialize($config);
if (! $this->upload->do_upload("file")) {
$errors++;
}
}
if ($errors > 0) {
echo $errors . "File(s) cannot be uploaded";
}
}
}
}
in controller i put code like bellow, but the filen can't move upload

Categories