PHP: uploaded images are not found in folder - javascript

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>

Related

Every time I delete a cookie, the content I wrote disappears

With full force I am creating a notepad that can permanently save the written contents.
Below is the actual code.
・ insertHTML & CSS
window.addEventListener('load', l => {
document.querySelector("body")
.insertAdjacentHTML('beforebegin', `
<!-- MEMO FORM -->
<div class="toolbar__centerfont" style=margin-top:50px;>
<font color="#4689FF" size="4.5";>Notepad No.1</font>
</div>
<textarea id="sample-text_1" class="My_textarea" rows="4" cols="24"></textarea>
<style>
#sample-text_1{
border:solid 1px blue;
outline:0;
min-height:80px;
min-width:235.85px;
font-size:9pt;}
</style>
<input type="button" id="sample-save_1" value="SAVE" onclick="savetext_1()" />
<style>
#sample-save_1{
display:block;
margin:0;
margin-top:-5.7px;
margin-left:0.5px;
width:45px;
height:18px;
font-size:8.5px;
background:#DDDDDD;
border-width:1px;
border-color:#23003a;
border-style:solid;
cursor:pointer;}
</style>
<input type="button" id="sample-delete_1" value="delete" onclick="deletetext_1()"/>
<style>
#sample-delete_1{
display:block;
margin:0;
margin-top:-18px;
margin-left:50px;
width:45px;
height:18.2px;
font-size:8.5px;
background:#DDDDDD;
border-width:1px;
border-color:#23003a;
border-style:solid;
cursor:pointer;}
</style>
<div class="toolbar__centerfont" style=margin-top:20px;>
<font color="#4689FF" size="4.5";>Notepad No.4</font>
</div>
<textarea id="sample-text_4" class="My_textarea" rows="4" cols="24"></textarea>
<style>
#sample-text_4{
border:solid 1px blue;
outline:0;
min-height:80px;
min-width:235.85px;
font-size:9pt;}
</style>
<input type="button" id="sample-save_4" value="SAVE" onclick="savetext_4()" />
<style>
#sample-save_4{
display:block;
margin:0;
margin-top:-5.7px;
margin-left:0.5px;
width:45px;
height:18px;
font-size:8.5px;
background:#DDDDDD;
border-width:1px;
border-color:#23003a;
border-style:solid;
cursor:pointer;}
</style>
<input type="button" id="sample-delete_4" value="delete" onclick="deletetext_4()" />
<style>
#sample-delete_4{
display:block;
margin:0;
margin-top:-18px;
margin-left:50px;
width:45px;
height:18.2px;
font-size:8.5px;
background:#DDDDDD;
border-width:1px;
border-color:#23003a;
border-style:solid;
cursor:pointer;}
</style>
<!-- End MEMO FORM -->
`);
});
・ JavaScript Processing content
window.addEventListener('load', ll => {
if (localStorage.getItem('memo_1') === null) {
return false;
}
var text_1 = localStorage.getItem('memo_1');
document.getElementById("sample-text_1").value = text_1;
});
// Text area_1 Save button processing
function savetext_1() {
var save_text_1 = document.getElementById("sample-text_1").value;
if (!save_text_1) {
return false;
}
localStorage.setItem('memo_1', save_text_1);
function set_color() {
document.getElementById("sample-text_1")
.style.backgroundColor = '#e1fddb';
}
let set_C = setInterval(set_color, 100);
function stop_color() {
clearInterval(set_C);
document.getElementById("sample-text_1")
.style.backgroundColor = '#fff';
}
setTimeout(stop_color, 2500);
}
// Text area_1 Delete button processing
function deletetext_1() {
if (localStorage.getItem('memo_1') === null) {
return false;
}
localStorage.removeItem('memo_1');
document.getElementById("sample-text_1").value = '';
}
I was quite happy with the moment it was completed, but there is one problem.
Every time you delete a cookie, the content you wrote down will be lost.
I want to keep what I wrote even if I delete the cookie.
Is that possible?
There is no basis, but here's what I've tried:
window.addEventListener('load', ll => {
if(localStorage.getItem('memo_4') === null){
return false;
}
var text_4 = localStorage.getItem('memo_4');
document.getElementById("sample-text_4").value = text_4;
document.cookie = "memo_4=save_text_4; expires=Sun, 01 Jan 2045 00:00:00 GMT";
let cookies_4_get = document.cookie;
cookies_4_get;
let cookies_4_set = encodeURIComponent(save_text_4);
document.cookie = 'memo_4' + cookies_4_set;
});
// Text area_4 Save button processing
function savetext_4(){
var save_text_4 = document.getElementById("sample-text_4").value;
if(!save_text_4){
return false;
}
localStorage.setItem('memo_4', save_text_4);
let cookies_4_get = document.cookie;
cookies_4_get;
document.cookie = "memo_4=save_text_4; expires=Sun, 01 Jan 2045 00:00:00 GMT";
//document.getElementById("sample-text_4").value = save_text_4;
function set_color(){
document.getElementById("sample-text_4")
.style.backgroundColor = '#e1fddb';
}
let set_C = setInterval(set_color, 100);
function stop_color(){
clearInterval(set_C);
document.getElementById("sample-text_4")
.style.backgroundColor = '#fff';
}
setTimeout(stop_color, 2500);
}
// Text area_4 Delete button processing
function deletetext_4(){
if(localStorage.getItem('memo_4') === null){
return false;
}
localStorage.removeItem('memo_4');
document.getElementById("sample-text_4").value ='';
document.cookie = "memo_4=; max-age=0";
}
Is it the limit of what can be done with the front end in the first place?
If so, how can I save my local storage permanently?
Operating environment
WINDOWS10, GoogleChrome 64bit
https://chrome.google.com/webstore/detail/user-javascript-and-css/nbhcbdghjpllgmfilhnhkllmkecfmpld

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

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
}

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........"
}
],
}

Add generated Javascript Events to generated HTML

I did a bunch of reaserch but it seems that I cant find a good answer to my question.
I have this code here:
while($row = mysqli_fetch_row($query)){
$result .= '
<script>
function Click'.$DOMid.'01(){answer("'.$DOMid.'","'.$row[2].'", "accept");}
function Click'.$DOMid.'02(){answer("'.$DOMid.'","'.$row[2].'", "decline");}
</script>
<div id = "'.$DOMid.'" style = "box-shadow: 5px 5px 2px #0f0f0a; margin: 10px; width:300px; padding:10px; border: 1px solid #0f0f0a;">
<p>
Freundschaftsanfrage von: '.$row[2].'
</p>
<button id = "'.$DOMid.'01" onclick="Click'.$DOMid.'01">Accept</button>
<button id = "'.$DOMid.'02" onclick="Click'.$DOMid.'02">Decline</button>
</div>
';
$DOMid = $DOMid+1;
}
$result .= '<script>
function answer(id, user, type){
$.ajax({
method: "POST",
url: "systems/friends_system.php",
data:{type: type, user, <?php echo json_encode($log_username);?>}
}).done(function(r){
if(r.charAt(0) == "_"){
window.location = "message.php?msg=" + r;
}else{
_("id").style.display = "none";
}
});
}
</script>';
echo $result;
exit();
its PHP code and it generates html and the javascript for each element.
But I think my javascript part isnt parsed at that point to the browser throws an error that the Clickxxx functions are not defined.
The resulting code looks like this:
<script>
function Click001(){answer("0","Drop", "accept");}
function Click002(){answer("0","Drop", "decline");}
</script>
<div id="0" style="box-shadow: 5px 5px 2px #0f0f0a; margin: 10px; width:300px; padding:10px; border: 1px solid #0f0f0a;">
<p>
Freundschaftsanfrage von: Drop
</p>
<button id="001" onclick="Click001">Accept</button>
<button id="002" onclick="Click002">Decline</button>
</div>
<script>
function answer(id, user, type){
$.ajax({
method: "POST",
url: "systems/friends_system.php",
data:{type: type, user, <?php echo json_encode($log_username);?>}
}).done(function(r){
if(r.charAt(0) == "_"){
window.location = "message.php?msg=" + r;
}else{
_("id").style.display = "none";
}
});
}
</script>
Onclick is a html event, and consider that the Click001 is a function, so call it with it's parentheses:
...button id="001" onclick="Click001()">...
you need to call your function, also this is a better use of js
while($row = mysqli_fetch_row($query)){
$result .= '
<script>
function Click(accept)
{
if(accept){
answer("'.$DOMid.'","'.$row[2].'", "accept");
}else{
answer("'.$DOMid.'","'.$row[2].'", "decline");
}
}
</script>
<div id = "'.$DOMid.'" style = "box-shadow: 5px 5px 2px #0f0f0a; margin: 10px; width:300px; padding:10px; border: 1px solid #0f0f0a;">
<p>
Freundschaftsanfrage von: '.$row[2].'
</p>
<button id = "'.$DOMid.'01" onclick="Click(true)">Accept</button>
<button id = "'.$DOMid.'02" onclick="Click(false)">Decline</button>
</div>
';
$DOMid = $DOMid+1;
}
$result .= '<script>
function answer(id, user, type){
$.ajax({
method: "POST",
url: "systems/friends_system.php",
data:{type: type, user, <?php echo json_encode($log_username);?>}
}).done(function(r){
if(r.charAt(0) == "_"){
window.location = "message.php?msg=" + r;
}else{
_("id").style.display = "none";
}
});
}
</script>';
echo $result;
I reinvented the Code
It looks like this now:
$result .= '
<div id = "'.$DOMid.'" style = "box-shadow: 5px 5px 2px #0f0f0a; margin: 10px; width:300px; height: 105px; padding:10px; border: 1px solid #0f0f0a;">
<p style = "height: 75px;">
<span style = "line-height: 75px; margin: auto 2px;">
Freundschaftsanfrage von: '.$row[2].'
</span>
<span style = "line-height: 75px; margin: auto 2px;">
<img src = "/user/'.$row[2].'/profile_pic.png" height = 60px width = 50px alt= "'.$row[2].'">
</span>
</p>
<button id = "'.$DOMid.'01" onclick="answer('.$DOMid.', \''.$row[2].'\', \'accept\')">Accept</button>
<button id = "'.$DOMid.'02" onclick="answer('.$DOMid.', \''.$row[2].'\', \'decline\')">Decline</button>
</div>';
every JavaScript is now in the original file and takes just parameters.
No Generic Javascript needed.

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