how to remove single uploaded file from jQuery in multiple file upload - javascript

I've searched everywhere and still don't get what I want.
I've following input field.
<div class="form-group gallery-add-button">
<label class="col-form-label" for="images">Image Gallery</label>
<div class="gallery-item-wrapper-0">
<input name="images[]" type="file" multiple class="filestyles gallery-images" id="photo-gallery" />
</div>
</div>
I've made image preview and on a remove button click, image preview is removed. In this case, I want to remove uploaded image from file upload field as well. Is there any way to achieve this.
I've found a way to remove all uploaded files but not a particular image.
Any kind of help is appreciated and if you need further information then feel free to ask.

I have a example delete image hope it will help you.
// Multiple images preview in browser
var imagesPreview = function(input, placeToInsertImagePreview) {
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
var htmlImage = '<div>';
htmlImage = htmlImage + '<img src="'+event.target.result+'" />';
htmlImage = htmlImage + '<input onclick="removeImage($(this))" type="button" value="Delete" />';
htmlImage = htmlImage + '</div>';
$($.parseHTML(htmlImage)).appendTo(placeToInsertImagePreview);
}
reader.readAsDataURL(input.files[i]);
}
}
};
function removeImage(item) {
//alert(item);
item.parent().remove();
}
$('#photo-gallery').on('change', function() {
imagesPreview(this, 'div.gallery');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="form-group gallery-add-button">
<label class="col-form-label" for="images">Image Gallery</label>
<div class="gallery-item-wrapper-0">
<input name="images[]" type="file" multiple class="filestyles gallery-images" id="photo-gallery" />
<div class="gallery"></div>
</div>
</div>

I wrote this code fast, hope it help
if it was what you need and you need help, I will do
var files=[];
$("#photo-gallery").change(function(){
for(var i=0;i<this.files.length;i++){
files.push(this.files[i]);
}
refreshFiles();
$(this).val('');
});
function refreshFiles(){
for(var i=0;i<files.length;i++){
$("#result").append('<div class="img-div"><span>'+(i+1)+'. '+files[i].name+'</span>x</div>');
}
}
$(document).on('click','.delete-image',function(){
var id=parseInt($(this).attr("image-id"));
files.splice(id,1);
$("#result").empty();
refreshFiles();
});
$(document).on('click','a',function(){
if($(this).attr("href")==="#"){
return false;
}
});
body{
font-family:arial;
}
#result{
margin:4px 0;
}
.img-div{
position:relative;
display:block;
width:200px;
height:40px;
line-height:40px;
margin:4px 0;
border:1px solid #999;
border-radius:6px;
padding:0 8px;
}
.delete-image{
position:relative;
display:inline-block;
float:right;
height:40px;
line-height:40px;
margin-left:20px;
text-decoration:none;
padding:0 8px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="form-group gallery-add-button">
<label class="col-form-label" for="images">Image Gallery</label>
<div class="gallery-item-wrapper-0">
<input name="images[]" type="file" multiple class="filestyles gallery-images" id="photo-gallery" />
</div>
</div>
<div id="result"></div>
</body>

this is the full example and I tested it and it works
sure you cant test upload here but try it in your local server
var files=[];
$("#photo-gallery").change(function(){
for(var i=0;i<this.files.length;i++){
files.push(this.files[i]);
}
refreshFiles();
});
function refreshFiles(){
for(var i=0;i<files.length;i++){
$("#result").append('<div class="img-div"><span>'+(i+1)+'. '+files[i].name+'</span>x</div>');
}
}
$(document).on('click','.delete-image',function(){
var id=parseInt($(this).attr("image-id"));
files.splice(id,1);
$("#result").empty();
refreshFiles();
});
$(document).on('click','a',function(){
if($(this).attr("href")==="#"){
return false;
}
});
$(document).on('click','#submit',function(){
if(files.length===0){
return false;
}
var fd=new FormData();
for(var i=0;i<files.length;i++){
fd.append('img_'+i,files[i]);
}
$.ajax({
url:"upload-images.php",
method:"post",
cache:false,
dataType:'json',
processData:false,
contentType:false,
data: fd,
success: function(data){
console.log(data);
}
});
});
.img-div{
position:relative;
display:block;
width:300px;
height:40px;
line-height:40px;
margin:4px 0;
border:1px solid #999;
border-radius:6px;
padding:0 8px;
}
.delete-image{
position:relative;
display:inline-block;
float:right;
height:40px;
line-height:40px;
margin-left:20px;
text-decoration:none;
padding:0 8px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group gallery-add-button">
<label class="col-form-label" for="images">Image Gallery</label>
<div class="gallery-item-wrapper-0">
<input name="images[]" type="file" multiple class="filestyles gallery-images" id="photo-gallery" />
</div>
</div>
<div id="result"></div>
<br>
<button id="submit">submit image</button>
and in you upload-images.php
foreach($_FILES as $file){
//your code
}

Related

How to convert the image into base64 encoded srting with multple image upload

I want to do a multiple file upload and I have to convert an image into base64 encoded string. I have one form and two form fields, like firstname & image upload. Suppose a user enters his name and he will upload two photos and he will click submit means, I want convert these two images into base64 string and I want to make my expected JSON format, I don't where I have to change from this code, please anyone update my code
var abc = 0; // Declaring and defining global increment variable.
$(document).ready(function() {
// To add new input file field dynamically, on click of "Add More Files" button below function will be executed.
$('#add_more').click(function() {
$(this).before($("<span/>", {
id: 'filediv'
}).fadeIn('slow').append($("<input/>", {
name: 'file[]',
type: 'file',
id: 'file'
}), $(" ")));
});
// Following function will executes on change event of file input to select different file.
$('body').on('change', '#file', function() {
if (this.files && this.files[0]) {
abc += 1; // Incrementing global variable by 1.
var z = abc - 1;
var x = $(this).parent().find('#previewimg' + z).remove();
$(this).before("<span id='abcd" + abc + "' class='abcd'><img id='previewimg" + abc + "' src=''/></span>");
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
$(this).hide();
$("#abcd" + abc).append($("<img/>", {
id: 'img',
src: 'x.png',
alt: 'delete'
}).click(function() {
$(this).parent().parent().remove();
}));
}
});
// To Preview Image
function imageIsLoaded(e) {
$('#previewimg' + abc).attr('src', e.target.result);
};
// Form Submit
$('#upload').click(function(e) {
e.preventDefault();
/*
var name = $(":file").val();
if (!name) {
alert("First Image Must Be Selected");
}*/
var firstName = $("#firstName").val();
console.log(firstName);
var data ={
"rentProperty":
{
"fname" : firstName,
},
"gallery": [
{
"image": "data:image/png/base64.ibokjnerkjdjflkdasafsdnmj........"
},
{
"image": "data:image/jpg/base64.ibokjnerkjdjflkdasafsdnmj........"
}
],
}
});
});
#import "http://fonts.googleapis.com/css?family=Droid+Sans";
form{
background-color:#fff
}
#maindiv{
width:960px;
margin:10px auto;
padding:10px;
font-family:'Droid Sans',sans-serif
}
#formdiv{
width:500px;
float:left;
text-align:center
}
form{
padding:40px 20px;
box-shadow:0 0 10px;
border-radius:2px
}
h2{
margin-left:30px
}
.upload{
background-color:red;
border:1px solid red;
color:#fff;
border-radius:5px;
padding:10px;
text-shadow:1px 1px 0 green;
box-shadow:2px 2px 15px rgba(0,0,0,.75)
}
.upload:hover{
cursor:pointer;
background:#c20b0b;
border:1px solid #c20b0b;
box-shadow:0 0 5px rgba(0,0,0,.75)
}
#file{
color:green;
padding:5px;
border:1px dashed #123456;
background-color:#f9ffe5
}
#upload{
margin-left:45px
}
#noerror{
color:green;
text-align:left
}
#error{
color:red;
text-align:left
}
#img{
width:17px;
border:none;
height:17px;
margin-left:-20px;
margin-bottom:91px
}
.abcd{
text-align:center
}
.abcd img{
height:100px;
width:100px;
padding:5px;
border:1px solid #e8debd
}
b{
color:red
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
<div id="maindiv">
<div id="formdiv">
<h2>Multiple Image Upload Form</h2>
<form enctype="multipart/form-data" action="" method="post">
First Name: <input type="text" name ="firstName" id="firstName"><br><br><br>
<div id="filediv"><input name="file[]" type="file" id="file" multiple/></div>
<input type="button" id="add_more" class="upload" value="Add More Files"/>
<input type="submit" value="Submit" name="submit" id="upload" class="upload"/>
</form>
</div>
</div>
</body>
My Expected answer with JSON Format
var data ={
"rentProperty":
{
"fname" : firstName,
},
"gallery": [
{
"image": "data:image/png/base64.ibokjnerkjdjflkdasafsdnmj........"
},
{
"image": "data:image/jpg/base64.ibokjnerkjdjflkdasafsdnmj........"
}
],
}

Jquery/Javascript changing img SRC with IF/ELSE statement

i am pretty new to javascript and I am not able to get an IF/ELSE statement to work in a kind of basic configurator I am experimenting, I am sure there's something dumb I am doing.
I have a main image that changes to show the result of a selection, the problem is that the IF statement doesn't seem to work properly, like if it wasn't going through the conditions: basically when selecting a color (black/silver) there are no problems, but when clicking on inserts it should change scr performing the if/else test to change the scr attribute accordingly.
var img = $("#picture");
$("#case_black").click(function() {
img.attr("src", "http://s32.postimg.org/xzqjausjp/black_b.jpg");
});
$("#case_silver").click(function() {
img.attr("src", "http://s32.postimg.org/j2n46ylmt/silver_s.jpg");
});
$("#insert_silver").click(function() {
if (img.src == "http://s32.postimg.org/xzqjausjp/black_b.jpg") {
img.attr("src", "http://s32.postimg.org/wfq99kqh1/black_s.jpg");
} else {
img.attr("src", "http://s32.postimg.org/j2n46ylmt/silver_s.jpg");
}
});
Here is a fiddle to help you help me:
https://jsfiddle.net/1qdwaa8o/
and a snippet:
var img = $("#picture");
$("#case_black").click(function() {
img.attr("src", "http://s32.postimg.org/xzqjausjp/black_b.jpg");
});
$("#case_silver").click(function() {
img.attr("src", "http://s32.postimg.org/j2n46ylmt/silver_s.jpg");
});
$("#insert_silver").click(function() {
if (img.src == "http://s32.postimg.org/xzqjausjp/black_b.jpg") {
img.attr("src", "http://s32.postimg.org/wfq99kqh1/black_s.jpg");
} else {
img.attr("src", "http://s32.postimg.org/j2n46ylmt/silver_s.jpg");
}
});
body{
background-color:black;
padding:0;
margin:0;
border:0;
text-align:center;
}
.main{
width:432px;
height:422px;
position:absolute;
display:inline-block;
margin-left:-216px;
margin-top:10%;
}
#img_wrapper{
width:350px;
margin-left:41px;
}
#selector_wrapper{
width:auto;
}
.selector_button{
width:50px;
height:50px;
border-radius:25px;
border:1px solid #1C1C1C;
margin: 0 10px;
cursor:pointer;
}
.clear{
clear:both;
}
#case_black{
background-image:url("http://s32.postimg.org/ipqo3nx1d/black.png");
float:left;
}
#case_silver{
background-image:url("http://s32.postimg.org/5qtwxrim9/silver.png");
float:left;
}
#insert_wood{
background-image:url("http://s32.postimg.org/ulderu3gh/wood.png");
float:left;
}
#insert_silver{
background-image:url("http://s32.postimg.org/5qtwxrim9/silver.png");
float:left;
}
#insert_black{
background-image:url("http://s32.postimg.org/ipqo3nx1d/black.png");
float:left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<body>
<div class="main">
<div id= "img_wrapper">
<img id= "picture" src="http://s32.postimg.org/xzqjausjp/black_b.jpg" alt="CD1000 with different finishes" />
</div>
<div id= "selector_wrapper">
<div id= "case">
<div class= "selector_button" id= "case_black"></div>
<div class= "selector_button" id= "case_silver"></div>
</div>
<div class= "clear"></div>
<div id= "inserts">
<div class= "selector_button" id= "insert_black"></div>
<div class= "selector_button" id= "insert_silver"></div>
<div class= "selector_button" id= "insert_wood"></div>
</div>
</div>
</div>
</body>
img is a jQuery object, therefore img.src will be undefined.
You need to test img[0].src or img.prop('src').
Get/set src of image using img.attr("src") and not img.src
Or you can make use of: img.get(0).src. img.get(0) is similar to document.querySelector('someSelectorToSelectYourImageAbove').src;

Button Effect OnClick Javascript

I need to create a button. The button must be similar to this:
And when i click to it, it must change in:
How can i do it? Thanks to all. I need i must use jquery, but i don't know how.
Same:
var value = 0;
$("#add_btn").on("click", function() {
$("#add_btn").hide();
$("#to_show").show();
value++;
$("#value").text(value);
});
$("#minus").on("click", function() {
value--;
$("#value").text(value);
});
$("#plus").on("click", function() {
value++;
$("#value").text(value);
});
#to_show {
display: none;
}
button{
background-color: red;
border: none;
width:40px;
height: 40px;
color: #fff;
font-size: 15px;
}
#value{
width: 40px;
display: inline-block;
text-align:center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button id="add_btn">Add</button>
<div id="to_show">
<button id="minus">-</button>
<div id="value"></div>
<button id="plus">+</button>
</div>
This is a working example by using Jquery and Css. Hide and Show are used to change the DOM elements.
$(document).ready(function() {
var count = 0;
$("#op").hide();
$("#btn").click(function() {
$("#result").text(count);
$("#btn").hide();
$("#op").show();
});
$("#plus").click(function() {
count++;
$("#result").text(count);
});
$("#minus").click(function() {
count--;
$("#result").text(count);
});
});
#btn, .operator{
background-color:rgb(224,0,0);
text-align:center;
cursor:pointer;
color:white;
}
#btn{
width:50px;
padding:5px;
}
.operator{
width:20px;
}
#op{
width:130px;
}
#op div{
float:left;
padding:5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="btn">click</div>
<div id="op"><div id="minus" class="operator">-</div><div id="result"></div><div id="plus" class="operator">+</div></div>
This is an example in javascript.
You might use jQuery.
CSS
.centerButton{
cursor:pointer;
text-align:center;
}
.smallButton{
width:20px;
height:20px;
}
html
<div class="centerButton" style="background:#f00;width:50px;height:25px;" id="addButton" >Add</div>
<div style="display:none" id="addButtonExpanded">
<div class="centerButton smallButton" style="float:left;background:#f00;" id="minusNumber" >-</div>
<div class="centerButton smallButton" style="float:left" id="number" >1</div>
<div class="centerButton smallButton" style="float:left;background:#f00;" id="plusNumber">+</div>
</div>
<input name="numberOfClicksInput" type="hidden" id="numberOfClicksInput"></input>
javascipt
$(document).ready(function() {
var numberOfClicks=0;
$("#addButton").click(function() {
$("#addButton").hide();
$("#addButtonExpanded").show();
numberOfClicks++;
$("#numberOfClicksInput").val(numberOfClicks);
});
$("#minusNumber").click(function() {
numberOfClicks--;
$("#numberOfClicksInput").val(numberOfClicks);
if(numberOfClicks==0){
$("#addButton").show();
$("#addButtonExpanded").hide();
} else {
$("#number").text(numberOfClicks);
}
})
$("#plusNumber").click(function() {
numberOfClicks++;
$("#numberOfClicksInput").val(numberOfClicks);
$("#number").text(numberOfClicks);
});
})
$( document ).ready(function() {
var numberOfClicks=0;
$(document).ready(function() {
$("#addButton").click(function(){
$("#addButton").hide();
$("#addButtonExpanded").show();
numberOfClicks++;
$("#numberOfClicksInput").val(numberOfClicks);
});
$("#minusNumber").click(function(){
numberOfClicks--;
$("#numberOfClicksInput").val(numberOfClicks);
if(numberOfClicks==0){
$("#addButton").show();
$("#addButtonExpanded").hide();
}else{
$("#number").text(numberOfClicks);
}
})
$("#plusNumber").click(function(){
numberOfClicks++;
$("#numberOfClicksInput").val(numberOfClicks);
$("#number").text(numberOfClicks);
})
});
})
.centerButton{
cursor:pointer;
text-align:center;
}
.smallButton{
width:20px;
height:20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<div class="centerButton" style="background:#f00;width:50px;height:25px;" id="addButton" >Add</div>
<div style="display:none" id="addButtonExpanded">
<div class="centerButton smallButton" style="float:left;background:#f00;" id="minusNumber" >-</div>
<div class="centerButton smallButton" style="float:left" id="number" >1</div>
<div class="centerButton smallButton" style="float:left;background:#f00;" id="plusNumber">+</div>
</div>
<input name="numberOfClicksInput" type="hidden" id="numberOfClicksInput"></input>

PHP: uploaded images are not found in folder

I want to upload multiple image in folder and also save in database. Problem is that, my images are not moving in folder. i don't know why? but same code is running on localhost. I paste my code please help me:
var abc = 0; // Declaring and defining global increment variable.
$(document).ready(function() {
// To add new input file field dynamically, on click of "Add More Files" button below function will be executed.
$('#add_more').click(function() {
$(this).before($("<div/>", {
id: 'filediv',
}).fadeIn('slow').append($("<input/>", {
name: 'file[]',
type: 'file',
id: 'file'
}), $("<br/><br/>")));
});
// Following function will executes on change event of file input to select different file.
$('body').on('change', '#file', function() {
if (this.files && this.files[0]) {
abc += 1; // Incrementing global variable by 1.
var z = abc - 1;
var x = $(this).parent().find('#previewimg' + z).remove();
$(this).before("<div id='abcd" + abc + "' class='abcd'><img id='previewimg" + abc + "' src=''/></div>");
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
$(this).hide();
$("#abcd" + abc).append($("<img/>", {
id: 'img',
src: 'x.png',
alt: 'delete'
}).click(function() {
$(this).parent().parent().remove();
}));
}
});
// To Preview Image
function imageIsLoaded(e) {
$('#previewimg' + abc).attr('src', e.target.result);
};
$('#upload').click(function(e) {
var name = $(":file").val();
if (!name) {
alert("First Image Must Be Selected");
e.preventDefault();
}
});
});
#import "http://fonts.googleapis.com/css?family=Droid+Sans";
form{
background-color:#fff
}
#maindiv{
width:960px;
margin:10px auto;
padding:10px;
font-family:'Droid Sans',sans-serif
}
#formdiv{
width:500px;
float:left;
text-align:center
}
form{
padding:40px 20px;
box-shadow:0 0 10px;
border-radius:2px
}
h2{
margin-left:30px
}
.upload{
background-color:red;
border:1px solid red;
color:#fff;
border-radius:5px;
padding:10px;
text-shadow:1px 1px 0 green;
box-shadow:2px 2px 15px rgba(0,0,0,.75)
}
.upload:hover{
cursor:pointer;
background:#c20b0b;
border:1px solid #c20b0b;
box-shadow:0 0 5px rgba(0,0,0,.75)
}
#file{
color:green;
padding:5px;
border:1px dashed #123456;
background-color:#f9ffe5
}
#upload{
margin-left:45px
}
#noerror{
color:green;
text-align:left
}
#error{
color:red;
text-align:left
}
#img{
width:17px;
border:none;
height:17px;
margin-left:-20px;
margin-bottom:91px
}
.abcd{
text-align:center
}
.abcd img{
height:100px;
width:100px;
padding:5px;
border:1px solid #e8debd
}
b{
color:red
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="image.js"></script>
<link rel="stylesheet" type="text/css" href="image_style.css">
<div id="filediv"><input name="file[]" type="file" id="file"/></div>
<input type="button" id="add_more" class="upload" value="Add More Files"/>
<button id="save" name="save" type="submit" class="btn btn-success btn-sm upload" id="upload">SAVE</button>
if(isset($_POST['save'])){
for($i = 0; $i < count($_FILES['file']['name']); $i++){
$image = $_FILES['file']['name'][$i];
$target_path = "http://rental.thedigitalmarketingonline.com/uploads/vehicle_snap/".$image;
if(($_FILES['file']['size'][$i] < 100000)){
if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)){
echo '<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
}else{
echo '<span id="error">please try again!.</span><br/><br/>';
}
}else{
echo '<span id="error">***Invalid file Size or Type***</span><br/><br/>';
}
}
}
first as #Gautam said, use form tag to be able to submit data,
second $target_path should be a real path such as "uploads/vehicle_snap/" as satya said
third this is not a good security practice, there is no filters to filter if this is an image or not so an attacker may upload php files and compromise your server/website
try filtering uploads by checking if the extension of the files is an image extension, you can do this by doing this:
$allowed_ext = ["png","jpg","jpeg","etc.."];
if(in_array(end(explode('.',$file['name'])),$allowed_ext)){
//uploading code goes inside here
}
I guess your data is not getting posted as you have not used form tags.
try using this and check if it works
<form action="upload.php" method="post" enctype="multipart/form-data">
<div id="filediv"><input name="file[]" type="file" id="file"/></div>
<input type="button" id="add_more" class="upload" value="Add More Files"/>
<button id="save" name="save" type="submit" class="btn btn-success btn-sm upload" id="upload">SAVE</button>
</form>

Uploading Multiple Files in Salesforce through Visualforce

I would like to upload multiple files in Salesforce using visualforce.
I can upload one file at a time.
But my requirement is, i want to display only one "add a file" button in visualforce page, when clicked over that button browse window should open and user selects a particular file and adds it. But after adding a file, the file path should be displayed as well as the same "add a file" button should be displayed below that which allows us to add another file. And after that we can save what we have added. It is same as adding attachments in our email.
Any help regarding this will be appreciated.
<!-- Use uploadFile function to attach multiple attachment.Update hardcoded parent id.-->
<apex:page>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript">
var __sfdcSessionId = '{!GETSESSIONID()}';
var filesToUpload = [];
var uploadedFile = 0;
</script>
<style>
.FilebuttonStyle{
font-family:Arial,'Helvetica Neue',Helvetica,sans-serif;
font-size:13px`enter code here`;color:#ffffff;
background-color: #169fcc !important;
text-decoration:none;
text-align:center;
border:1px solid #1691ba !important;
line-height: 25px;!important;
border-radius:4px;
display:inline-block;
cursor:pointer;
width:85px;
}
td.fileRow {
overflow: hidden;
font-family:Arial,'Helvetica Neue',Helvetica,sans-serif;
font-size:13px;color:#ffffff;
background-color: #8db728;
text-decoration:none;
text-align:center;
border:1px solid #6c8049;
line-height: 32px;!important;
border-radius:4px;
//padding-left:10px;
//padding-right:10px;
background-image:linear-gradient(top,#9dcc3d,#7da223);
background-image:-o-linear-gradient(top,#9dcc3d,#7da223);
background-image:-moz-linear-gradient(top,#9dcc3d,#7da223);
background-image:-webkit-linear-gradient(top,#9dcc3d,#7da223);
background-image:-ms-linear-gradient(top,#9dcc3d,#7da223);
display:inline-block;
cursor:pointer;
width:120px;
overflow: hidden;
}
td.fileRow input {
display: block !important;
width: 157px !important;
height: 57px !important;
opacity: 0 !important;
overflow: hidden !important;
}
.fileCheckBox {
width: 16px;
height: 16px;
display: inline-block;
margin: 3px 5px 3px 3px;
background-color: white;
//box-shadow: 0px 0px 1px #b0b3ae;
text-align: center;
vertical-align: top;
}
.FilebuttonGroup{
float:right;
padding-right: -70px!important;
}
</style>
<script src="/soap/ajax/32.0/connection.js" type="text/javascript"></script>
<script type="text/javascript">
function uploadFile(parentId)
{
// var input = $('.fileInput')[0];
//var input = document.getElementById("file-input");
// var filesToUpload = input.files;
$("input[type=file]").each(function(){
filesToUpload.push($(this)[0].files[0]);
});
//console.log(filesToUpload);
for(var i = 0, f; f = filesToUpload[i]; i++)
{
var reader = new FileReader();
// Keep a reference to the File in the FileReader so it can be accessed in callbacks
reader.file = f;
reader.onload = function(e)
{
var att = new sforce.SObject("Attachment");
att.Name = this.file.name;
att.ContentType = this.file.type;
att.ParentId = parentId;
var binary = "";
var bytes = new Uint8Array(e.target.result);
var length = bytes.byteLength;
for (var i = 0; i < length; i++)
{
binary += String.fromCharCode(bytes[i]);
}
att.Body = (new sforce.Base64Binary(binary)).toString();
sforce.connection.create([att],
{
onSuccess : function(result, source)
{
if (result[0].getBoolean("success"))
{
console.log("new attachment created with id " + result[0].id);
}
else
{
console.log("failed to create attachment " + result[0]);
}
},
onFailure : function(error, source)
{
console.log("an error has occurred " + error);
}
});
};
reader.readAsArrayBuffer(f);
}
}
function addRow(tableID){
var row = '<tr><td><input type="checkbox" onclick="processCheckbox()" name="chk" class="fileCheckBox"/</td><td class="fileRows"><input type="file"/> </td></tr>';
$('#'+tableID).append(row);
}
function deleteRow(tableID)
{
try
{
var table=document.getElementById(tableID);
var rowCount=table.rows.length;
for(var i=0;i<rowCount;i++)
{
var row=table.rows[i];
var chkbox=row.cells[0].childNodes[0];
if(null!=chkbox&&true==chkbox.checked)
{
table.deleteRow(i);
filesToUpload.splice(i, 1);
// console.log(filesToUpload);
rowCount--;
i--;
}
}
processCheckbox();
}
catch(e)
{
alert(e);
}
}
function processCheckbox(){
$("[id$='_remove']").hide();
var checkCount=0;
$("#dataTable input[type='checkbox']").each(function(){
if($(this).is(':checked'))
{
checkCount++;
}
});
if(checkCount >0){
$("[id$='_remove']").show();
}
}
</script>
<div class="FilebuttonGroup">
<input type="button" value="Delete Row" id="_remove" onclick="deleteRow('dataTable')" class="FilebuttonStyle" title="Delete Row"/>
<input type="button" value="Add Row" onclick="addRow('dataTable')" id="_add" class="FilebuttonStyle" title="Add Row"/>
</div>
<table id="dataTable" >
<tbody>
<tr>
<td> </td>
<td class="fileRows"> <input type="file" class="fileInput"/> </td>
<td></td>
</tr>
</tbody>
</table>
<!--Correct this attachment parentid -->
<input type="button" value="Upload" onclick="uploadFile('5009000000cjeZn')" title="Upload"/>
<div id="statusid"></div>
<script>
$(document).ready(function(){
$("[id$='_remove']").hide();
$("[id$='attachmentBlock']").find('.pbSubsection').attr({'style':'margin-right:-70px !important;'});
});
</script>
</apex:page>
You can upload multiple attachment using ajax asynchronously. You need to update the parent record id of attachment. Find the code at:
https://github.com/DebGit/Dev_2015_org1/blob/master/src/pages/FileUploaderAjax.page

Categories

Resources