Html multiple file input - javascript access and delete files - javascript

Im trying to delete values from a html file input.
<input type="file" name="images" id="i1" class="imageup" multiple />
I cant seem to access the .files array to delete one of the values. I had tried using a hidden input type with the file value but i dont think this can be done....so im trying to access the input element to delete!
There is a fiddle below of all the code. There is a lot there to replicate the situation but the code controlling the delete event is about half way down the js.
http://jsfiddle.net/dheffernan/ryrfS/1
Does anyone have a method of accessing for example the 3rd inputted value of the multiple file upload and deleting?
The js code below- using .splice attempt.
var files=jQuery('#i'+inputid)[0].files;
for (var i = 0; i < files.length; i++) {
console.log(files[i].name);
}
var inputname= 3;
jQuery('#i'+inputid).splice(inputname, 1);
// no files are being deleted!!!
console.log('2nd test');
var files=jQuery('#i'+inputid)[0].files;
for (var i = 0; i < files.length; i++) {
console.log(files[i].name);
}
}

using html5 FormData solution:
Basically add the images to FormData, submit it using ajax and return the urls from where i uploaded them (i included the php for wordpress). I removed all data validation from js code and php code to keep it short + i still need a workaround for ie9 / older vers of browsers.
jQuery code:
jQuery(document).on('change', '.imageup', function(){
var id= jQuery(this).attr('id');
var length= this.files.length;
if(length>1) {// if a multiple file upload
var images = new FormData();
images.append('action', 'uploadimg'); //wordpress specific add functionname
jQuery.each(event.target.files, function(key, value ){
images.append(key, value);
});
jQuery.ajax({
url: '/wp-admin/admin-ajax.php',
type: 'POST',
data: images,
cache: false,
processData: false,
contentType: false,
success: function(data) {
var obj= JSON.parse(data);
jQuery.each(obj,function(key, value){
if(key!='errors') {
var ind = value.lastIndexOf("/") + 1;
var filename = value.substr(ind);
//do something here with filename
console.log(filename);
}
});
}//end of success function
}); //end ajax
}
});
php code wordpress, if not using wordpress change the above url, etc..
function uploadimg() {
$error = false;
$files = array();
if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' );
$upload_overrides = array( 'test_form' => false );
$url=array();
foreach($_FILES as $file){
$uploadimage= $file;
$movefile = wp_handle_upload( $uploadimage, $upload_overrides );
if ( $movefile ) {
if($movefile['url']) {
$url[]=$movefile['url'];
} else {
$url['errors'][]="error ".$movefile['file']." is not valid";
}
} else {
}
}
$url['errors'][]="error is not valid";
echo json_encode($url);
exit;
}
add_action('wp_ajax_uploadimg', 'uploadimg');
add_action('wp_ajax_nopriv_uploadimg', 'uploadimg');

Edit
Try Blob , FileReader ?
see
https://developer.mozilla.org/en-US/docs/Web/API/Blob
https://developer.mozilla.org/en-US/docs/Web/API/File
How do I read out the first 4 bytes in javascript, turn it into an integer and remove the rest?

Related

File upload not working in PHP , $_POST['file'] , not able to extract file

I have the following HTML code:
<form action="mail/filesend.php" method="POST" accept-charset="utf-8" enctype="multipart/form-data" validate>
<div class="input-wrpr">
<input type="file" name="files[]">
</div>
<button type="submit">
Send File
</button>
</form>
And then the following file upload code in jQuery:
$(function () {
let files = null;
$('input[type="file"]').on('change' , (e) => {
files = e.target.files;
});
$('form').submit(function(e){
e.stopPropagation();
e.preventDefault();
let data = new FormData();
// files = $('input[type="file"]')[0].files;
$.each(files, function(key, value){
data.append(key, value);
});
console.log(data.getAll('0'));
// console.log(data);
$.ajax({
type: $(this).attr('method'),
url : $(this).attr('action'),
data: data,
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
data : data
}).done(function(data){
// console.log(data);
if (! data.success) {
// console.log(data.errors);
/*for(let er in data.errors) {
console.log(data.errors[er])
}*/
console.log(data);
} else {
/* else condition fires if form submission is successful ! */
console.log(data.file);
}
}).fail(function(data){
console.log(data);
});
});
});
And the following PHP code for testing :
<?php
// You need to add server side validation and better error handling here
$data = array();
if(isset($_FILES['files'])) {
$data = array('file' => 'I a in if');
}
else {
$data = array('file' => 'I am in else');
}
echo json_encode($data);
?>
Now when i check my console i see that the PHP if condition is not passing , that is it is unable to detect:
isset($_POST['files'])
Why is this happening ? I have tried using isset($_FILES['files']), also I have tried renaming my html file input field to just files instead of files[] , but this does't seem to work , What am I doing wrong ?
I was following the tutorial HERE. But somehow the example I have created just does't work.
Try to print_r($_FILES) and check if it shows an array of file,
If it does, use the same key in $_FILES['same_key_here'] and it supposed to work,
Let me know if it doesn't
If you want to send files, do something like this.
This may help you.
var fileInput = $("#upload_img")[0]; // id of your file
var formData = new FormData();
formData.append("image_file",fileInput.files[0]); //'xmlfile' will be your key
Check in your php code like,
echo $_POST['image_file'];

Unable implement a functionality to upload multiple images to the server

Currently, I have the following code that will allow me to upload only one image to the server at the time.
But what I want to do is to upload multiple images. I don't mind if it will send multiple request to the server, but I want to replace the following code, so that I can drag and drop or select multiple images at a time and send it with ajax. How will I be able to achieve this ?
I tried to use some libraries that I found on the web such as dropzone.js, but it seems like it doesnt do the trick. Some simple samples or tips would be great ! I would love to hear from you !
HTML code
<div>
<input type="file" name="mydata[]"/>
<span class="btn" onclick="imgToMyServer('$(this));">Fly Me to the Server ! </span>
</div>
JS side
<script>
function imgToMyServer(ob) {
var form = $('<form />');
var files = ob.prev('input[type="file"]');
var simplefile = files.prop('files')[0];
var Myname = simplefile.name;
var input = $('<input name="mydata[][my_path]" value="path/' + Myname+ '"/>');
switch (simplefile.type) {
case "image/jpeg":
break;
case "image/png":
break;
case "image/gif":
break;
default:');
return false;
break;
}
files.after(files.clone());
files.appendTo(form);
input.appendTo(form);
datas = new FormData(form[0]);
$.ajax({
type: 'post',
processData: false,
contentType: false,
data: datas,
url: "https//www.sample.com/uploads_my_images",
async: true,
success: function (res) {
//Just happy
}
});
}
</script>
What you need its quite simple first you need to add the multiple attribute on the file input type so that it allows you to select multiple files.
Then you need to check the number of images that are selected, then loop through the array of images that are selected then append the images dynamically to the form data :
<script src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<div>
<input type="file" name="mydata[]" id ="multiFiles" multiple="multiple">
<button id="upload" class="btn">Fly Me to the Server !</button>
<div id="msg"></div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('#upload').on('click', function (e) {
e.preventDefault();
var form_data = new FormData(); //create form data object
var num_files = document.getElementById('multiFiles').files.length;
for (var x = 0; x < num_files; x++) {
form_data.append("files[]", document.getElementById('multiFiles').files[x]); //append the files to the form data object
}
$.ajax({
url: 'upload.php',
dataType: 'text', // what to expect back from the PHP script, could be json,html
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$('#msg').html(response); // display success response from the PHP script
},
error: function (response) {
$('#msg').html(response); // display error response from the PHP script
}
});
});
});
</script>
server :
<?php
if (isset($_FILES['files']) && !empty($_FILES['files'])) {
$no_files = count($_FILES["files"]['name']);
for ($i = 0; $i < $no_files; $i++) {
if ($_FILES["files"]["error"][$i] > 0) {
echo "Error: " . $_FILES["files"]["error"][$i] . "<br>";
} else {
if (file_exists('uploads/' . $_FILES["files"]["name"][$i])) {
echo 'File already exists : uploads/' . $_FILES["files"]["name"][$i];
} else {
move_uploaded_file($_FILES["files"]["tmp_name"][$i], 'uploads/' . $_FILES["files"]["name"][$i]);
echo 'File successfully uploaded : uploads/' . $_FILES["files"]["name"][$i] . ' ';
}
}
}
} else {
echo 'Please choose at least one file';
}
NB: I did not do any validation of the file uploaded, I just uploaded
straight, you need to validate in both the client and the server side.

How can I use AJAX to pass selected files to a PHP file?

I have 2 forms:
Form A contains field name, age, address, email and a hidden text field for the names of images which are going to be uploaded in form B.
Form B contain an input type File so users can browse and select their photos.
I used Jquery to trigger an function upload those images after they are selected.
I'm stuck at the step passing the selected images array to the PHP file that handles upload progress via AJAX.
I searched but there were no samples for my problem. I appreicate any help.
<form action="upload_img.php" name="form_B" method="POST" enctype="multipart/form-data">
Select images: <input type="file" name="selected_imgs[]" id="selected_imgs" multiple>
</form>
<script type="text/javascript">
$(function() {
$("input:file").change(function (){
ajax_upload();
});
});
</script>
You can try below code
function uploadFile(){
var file = $('#filetoupload');
var valid_extensions = /(\.jpg|\.jpeg|\.gif|\.doc|\.xls|\.txt|\.rtf|\.pdf)$/i;
var isvalid = true;
//for every file...
var input = document.getElementById('filetoupload');
for (var x = 0; x < input.files.length; x++) {
if(!valid_extensions.test(input.files[x].name)){
isvalid = false;
}
}
if(isvalid == true ){
var formData = new FormData();
for (var x = 0; x < input.files.length; x++) {
formData.append("filetoupload[]",input.files[x]);
}
$.ajax({
url: 'localhost/upload.php', //server script to process data
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false,
dataType: "json",
success:function (data){
alert("File Uploaded");
// data.src return from your server
// so you can display image in page using <img> tag
},
error:function (data){
alert("Error!");
}
});
}else{
alert("File format not supported!");
return false;
}
return true;
}

No file being uploaded while uploading multiple files using AJAX

I am trying to upload multiple files with only 1 AJAX request. But I am facing some problems and they are:
UPDATE
No file is being uploaded to the server
It seems to me that multiple AJAX requests are being made as AJAX is inside the for loop.
How to sort these problems?
HTML
<!--<form id="fileupload" method="POST" enctype="multipart/form-data">-->
<input type="file" multiple name="uploadfile[]" id="uploadfile" />
<!--</form>-->
JS
$("#uploadfile").change(function(){
//submit the form here
//$('#fileupload').submit();
var files = $("#uploadfile")[0].files;
for (var i = 0; i < files.length; i++){
//alert(files[i].name);
var data = files[i].name;
$.ajax({
type:'POST',
url: 'mupld.php',
data: data
});
}
//var files = $('#uploadfile').prop("files"); //files will be a FileList object.
//alert(files);
//var names = $.map(files, function(val) { return val.name; }); //names is an array of strings (file names)
});
PHP
<?php
if(isset($_FILES['uploadfile'])){
$errors= array();
foreach($_FILES['uploadfile']['tmp_name'] as $key => $tmp_name ){
$file_name = $key.$_FILES['uploadfile']['name'][$key];
$file_size =$_FILES['uploadfile']['size'][$key];
$file_tmp =$_FILES['uploadfile']['tmp_name'][$key];
$file_type=$_FILES['uploadfile']['type'][$key];
if($file_size > 2097152){
$errors[]='File size must be less than 2 MB';
}
//$query="INSERT into upload_data (`USER_ID`,`FILE_NAME`,`FILE_SIZE`,`FILE_TYPE`) VALUES('$user_id','$file_name','$file_size','$file_type'); ";
$desired_dir="storage";
if(empty($errors)==true){
if(is_dir($desired_dir)==false){
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if(is_dir("$desired_dir/".$file_name)==false){
move_uploaded_file($file_tmp,"$desired_dir/".$file_name);
}
else{ // rename the file if another one exist
$new_dir="$desired_dir/".$file_name.time();
rename($file_tmp,$new_dir) ;
}
//mysql_query($query);
}
else{
print_r($errors);
}
}
if(empty($error)){
echo "Success";
}
}
?>
js at Question does not appear to upload File object, but File.name at var data = files[i].name; ? <!-- --> is not valid comment in javascript
Try using FormData()
$("#uploadfile").change(function() {
var files = $("#fileupload")[0];
$.ajax({
type:"POST",
url: "mupld.php",
data: new FormData(files),
processData: false,
contentType: false
});
});
Use it
AJAX File Upload plugin
<pre>
$("#uploadfile").change(function(){
$.ajaxFileUpload
(
{
url:'mupld.php',
secureuri:false,
fileElementId:'uploadfile[]',
dataType: 'html',
data:{},
success: function (data, status)
{
},
error: function (data, status, e)
{
}
}
);
});
</pre>

Code Igniter File Uploading Class with Jquery Ajax

So all I am trying to accomplish is simply upload a file with codeigniter using the File Uploading Class
For my controller I have the following code:
function do_upload()
{
$config['upload_path'] = './assets/productImages/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
var_dump($error);
}
else
{
$data = array('upload_data' => $this->upload->data());
}
}
And then my form is as follows:
$data['productImage'] = array(
"name" => "userfile",
"id" => "product_image",
);
// displays out as:
<input type="file" name="userfile" value="" id="product_image">
My javascript is as follows which uses an onchange action to trigger the upload process.
$("document").ready(function(){
$("#product_image").change(function() {
var path = $(this).val();
var dataString = 'userfile=' + path;
//alert(dataString); return false;
$.ajax({
type: "POST",
url: "/account/do_upload/",
data: dataString,
success: function(data) {
alert(data);
}
});
return false;
});
});
When I run this code, I receive this message in the javascript alert
You did not select a file to upload.
What do I need to add to make this work? I'm guessing it has something to do with processing the upload through the javascript ajax.
*UPDATE DUE TO COMMENTS *
My form tag is as follows:
$data['newPostForm'] = array('id' => 'newPostForm', 'type' => 'multipart');
// And echoes out as :
<form action="http://myurl.com/index.php/account/submitPost" method="post" accept-charset="utf-8" id="newPostForm" type="multipart">
Your codeigniter code looks fine.
The problem is that you can't upload files directly through Ajax. You need to do it though an iframe.
This plugin here works a treat.
Or if you only need it to work in html 5 then this should do the treat
http://www.devbridge.com/projects/html5-ajax-file-upload/

Categories