How can I do update with using same id but different content? - javascript

Currently, I working on form that got an input for image file. After browse image then upload it I will get the id for the image. Here is my code for POST.
$("#smallpicture_id").change(function () {
displayAndShowImage(this,'#smallimg','#smallimg');
});
$("#largepicture_id").change(function () {
displayAndShowImage(this,'#largeimg','#largeimg');
});
function displayAndShowImage(input,targetHtmlElementName) {
if (input.files && input.files[0]) {
var files = input.files;
var reader = new FileReader();
reader.onload = function (e) {
$(targetHtmlElementName).attr('src', 'images/uploading.gif');
var formData = new FormData();
formData.append('userfile',files[0],files[0].name);
createImage(
config,
formData,
{
onSuccess : function(data) {
$(targetHtmlElementName).attr('src', e.target.result);
$.cookie(input.id, data);
console.log("Image has been save - Received ID: " + data + " saved in the cookie " + input.id);
},
onError : function(jqXHR, status) {
$(targetHtmlElementName).attr('src', 'images/img-error.png');
console.log("ERROR " + jqXHR.responseText + "\r\nstatus = " + status);
}
}
);
}
reader.readAsDataURL(files[0]);
}
}
Ajax
function createImage(cfg,formData,callbacks) {
var xhr = new XMLHttpRequest();
xhr.open('POST', cfg.url + "/image/", true);
xhr.onload = function () {
if (xhr.status === 200) {
// File(s) uploaded.
callbacks.onSuccess(xhr.responseText.trim());
} else {
callbacks.onError(xhr);
}
};
xhr.send(formData);
}
My question is how can I update / delete for my image with using the same id that given to the image. I already can do POST and GET but I still don't get any idea how to update and delete.

You can append two string in FormData query identifier and ID (only in case of update & delete), like
formData.append('queryType', 'DELETE')
formData.append('imageID', input.id)
On server side code (where you have added code for saving new Image) you have to add condintion like this
<?php
$identifier=$_POST['queryType'];
if($identifier=="NEW") {
//save file with new ID and return ID
} elseif ($identifier=="UPDATE")
//update Image Data ($_FILE) with ID appended in formdata
} elseif ($identifier=="DELETE")
//Delete existing image at ID specified
}
?>
hope this may help.

You can give your elements specific classname for each upload process, which have same id, then run displayAndShowImage function for only elements has "update-this" classname.
$("#smallpicture_id").change(function () {
$(this).addClass("update-this"); // add update-this class
$(".update-this").not($(this)).removeClass("update-this"); // remove all update-this classnames from all other ones
// then run your function for only element which has update-this classname
displayAndShowImage(this,'.update-this');
});

Related

How set background img from MySQL database in javascript

I am using codelgniter, vanilla javascript , ajex, css, MySQL only
I want set background of image which store in mySQL database
The following code is working very well & not get error but problem is that how can I set background of image storage in database
Note the image is must be get using ajex ( xhr request respond )
The javascript create following css dynamically
.demo0::before {
Background: URL ("path");
}
.demo1::before {
Background: URL ("path");
}
.demo2::before {
Background: URL ("path");
}
And so on
I have following vanilla javascript
background_img=www.Demo.jpg; //temporary set
d_no=0;
Style0 = document.getElementByITagName("style")[0];
Style0.type="text/css";
Data=style0.innerHTML;
style0.innerHTML = data + "demo" d_no+"before { background: url("+ background_img +" );}";
d_no=d_no+1;
it is simple but tricky you need to make controller model of getting img src/url value in css or javascript or html url or src is may be path or image value
use following code
controller
<?php
class cover_img extends CI_Controller
{
public function index()
{
$getRequestData=stripslashes(file_get_contents("php://input"));
$datas=json_decode($getRequestData,true);
$this->load->model("cover_img_model","cim");
$this->cim->get_cover_img($datas["f_id"]);
}
}
?>
model
<?php
class cover_img_model extends CI_Model
{
function get_cover_img($username)
{
// echo $username;
$data=$this->db->query("select cover from user_detail where user_name='$username'");
foreach ($data->result_array() as $row)
{
echo "data:image/jpg;charset=utf8;base64,";
echo base64_encode($row['cover']);
}
}
}
?>
vanilla javascript
style0=document.getElementsByTagName("style")[0];
style0.type="text/css";
ccs_data=style0.innerHTML+"\n \n";
xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost/CI-social-media/index.php/cover_img", false);
obj = {"f_id":f_id}; // f_id is primary key field value for get the img using where condition in mysql change this f_id dynamically for getting different img
// alert(f_id);
data = JSON.stringify(obj);
xhr.onload = () => {
if (xhr.status == 200) {
if (xhr.response) {
style0.innerHTML = ccs_data +"\t "+ ".demo" + d_no + "::before{ \n\t\t background: url('"+xhr.responseText+"'); \n\t} ";
// alert(xhr.responseText);
}
else {
alert("something want wrong try agin later")
}
}
else {
alert("Something Want Wrong Try agin");
}
}
xhr.send(data);
document.getElementsByTagName('head')[0].appendChild(style0);
d_no=d_no+1;
If you get binary image from server:
<script>
fetch("/image") // url of binary image response
.then((response) => response.blob())
.then((myBlob) => {
const objectURL = URL.createObjectURL(myBlob);
document.querySelector('#body') // element selector, which has background
.style.backgroundImage = `url(${objectURL})`
});
</script>
If you have static image
<script>
fetch("/get-image.php") // url of php script, which returns url to static image
.then((response) => response.text())
.then((src) => {
document.querySelector('#body') // element selector, which has background
.style.backgroundImage = `url(${src})`
});
</script>

How to insert image in sqlite?

I am developing a cross platform application using cordova.
I need to insert image inside sqlite. I am getting lots of code for android but I find it difficult to do with javascript. I am getting err.code:5 when I run the following code in my iPhone.
document.addEventListener("deviceready", onDeviceReady, false);
var img;
var currentRow;
var b = new Blob();
function previewFile() {
// var preview = document.querySelector('img');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
// var package_name = document.getElementById("pr").value;
reader.onloadend = function () {
// img = reader.result;
if(file.type.match('image.*'))
{
img = reader.result;
// ref.push({"image":image,"service":arr,"package_name":package_name});
}
else
{
alert("select an image file");
}
}
if (file) {
reader.readAsDataURL(file);
} else {
preview.src = "";
}
var image1 = encodeURI(img);
// var b = new Blob();
b = image1;
console.log(b);
console.log(image1);
//document.write('<img src="'+image+'"/>');
}
function onDeviceReady() {
var db = window.sqlitePlugin.openDatabase({name:"sqlite"});
db.transaction(populateDB, errorCB, successCB);
}
function populateDB(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id INTEGER PRIMARY KEY AUTOINCREMENT, name,number,image BLOB)');
}
function insertDB(tx) {
tx.executeSql('INSERT INTO DEMO (name,number,image) VALUES ("' +document.getElementById("txtName").value
+'","'+document.getElementById("txtNumber").value+'","' +b+ '")');
}
function goInsert() {
var db = window.sqlitePlugin.openDatabase({name:"sqlite"});
db.transaction(insertDB, errorCB, successCB);
}
My html code:
<input type="file" onchange="previewFile()">
<button onclick="goInsert()">Insert</button>
How to do this. Can someone help me? Thanks in advance...
Convert your image (in memory) to a byte[] and then save it your sql db as varbinary(max).
Inserting blob into database will make your application slow as well as laggy, instead save the path of the selected picture into the database.
And when you want to upload the image to the server use
fileupload feature of cordova.
If you are getting image from server than download that image locally and save that path into the database
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
function onFileSystemSuccess(fileSystem)
{
fileSystem.root.getFile(
"dummy.html", {create : true, exclusive : false},
function gotFileEntry(fileEntry)
{
var sPath = fileEntry.fullPath.replace("dummy.html", "");
var fileTransfer = new FileTransfer();
fileEntry.remove();
fileTransfer.download(
"http://www.w3.org/2011/web-apps-ws/papers/Nitobi.pdf",
sPath + "theFile.pdf",
function(theFile)
{
console.log("download complete: " + theFile.toURI());
showLink(theFile.toURI());
},
function(error)
{
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code: " + error.code);
}
);
}, fail);
}, fail);

Cordova App : How to get the actual path of file

I'm using Cordova to make android and iOS app, now I would like to check if file already exist in the dirctory.
First I download file from server and save it locally using the code below
$scope.downloadFile = function(){
alert(cordova.file.dataDirectory)
var fileTransfer = new FileTransfer();
var uri = encodeURI("http://example.com/files/th/001.mp3");
var downloadPath = cordova.file.dataDirectory+'001.mp3'; // ANDROID
fileTransfer.download(
uri,
downloadPath,
function(entry) {
$scope.savepath = entry.toInternalURL();
alert("download complete: " + entry.toURL());
alert('saved at : '+entry.toInternalURL());
},
function(error) {
alert("download error source " + error.source);
alert("download error target " + error.target);
alert("upload error code" + error.code);
},
false,
{
headers: {
"Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
}
}
);
}//End DownloadFile
and I would like to check if the file already exist using checkIfFileExists(path) method
function checkIfFileExists(path){
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem){
//alert('result: '+JSON.stringify(fileSystem.root))
fileSystem.root.getFile(path, { create: false }, fileExists, fileDoesNotExist);
}, getFSFail); //of requestFileSystem
}
function fileExists(fileEntry){
alert("File " + fileEntry.fullPath + " exists!");
}
function fileDoesNotExist(){
alert("file does not exist");
}
function getFSFail(evt) {
console.log(evt.target.error.code);
}
I checked on my phone, the file is already saved to Android/data/com.myname.myappname/file/001.mp3
but the problem is the code always show file does not exist whenever I use the path like
cordova.file.dataDirectory+'001.mp3';
or cdvfile://localhost/persistent/files/001.mp3
or 'cdvfile://localhost/files/001.mp3'
so I would like to ask that the real path that I need to use to check if the file exist or not.
Please provide me any suggestion.
Regards.
Do you need to use or CheckFileExists? You could try using Phonegap's FileReader method?
var reader = new FileReader();
var fileSource = cordova.file.dataDirectory+'001.mp3'
reader.onloadend = function(evt) {
if(evt.target.result == null) {
// Null? You still have a problem: file doesn't exist.
} else {
// Otherwise the file exists.
}
};
//Check if the file exists
reader.readAsDataURL(fileSource);

How to get base64 from input file in IE without using FileReader or HTML5

I hope I can have help from you. I need to get a file from an HTML input file element.
This is the HTML:
<input type="file" name="allegatoImg" id="allegatoImg" onchange="javascript:readURL(this)"/>
And this is JavaScript:
function readURL(input) {
var mimeType;
if (window.FileReader) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
var dataURL = e.target.result;
mimeType = dataURL.split(",")[0].split(":")[1].split(";")[0];
if (mimeType == 'image/jpeg') {
jQuery('#imgallegato').attr('src', e.target.result);
//jQuery('#fotoTemp').attr('src', e.target.result);
provaInvioImgSrcToServer();
} else {
alert('Errore nella lettura del file. Controllare che sia stato caricato un file con estensione jpeg.');
return;
}
};
reader.readAsDataURL(input.files[0]);
}
} else {
f = document.dettRichAbbForm;
document.getElementById("imgallegato").src = "file:///" + input.value;
var estensione = ctrlExtensionFileIE(input.value);
alert('path file = ' + jQuery("#imgallegato").attr('src') );
if (estensione=='jpg' || estensione=='jpeg') {
provaInvioImgSrcToServer();
} else {
alert('Error in reading file');
return;
}
}
}
function provaInvioImgSrcToServer() {
var urlToCall = provaInvioImgSrcToServerUrl;
alert('img path = ' + jQuery("#imgallegato").attr('src'));
jQuery.ajax({
cache : false,
type : "POST",
timeout : 5000,
url : urlToCall,
data : {imgSource: jQuery("#imgallegato").attr('src')},
success : function(result) {
ritagliaImg();
},
error : function(errorMsg) {
//gestAjaxCallError(errorMsg, divResultBodId, divResultBodId);
alert('Errore nel caricamento dell\'immagine selezionata.');
}
});
}
function ctrlExtensionFileIE(value) {
var splittedVal = value.split(".");
return splittedVal[1];
}
I'm working on Liferay 5.1 with an old version of jQuery so I can't use HTML5 with canvas element, because I should load the image from the input file into a Jcrop element.
My problem is linked to this part of the code:
f = document.dettRichAbbForm;
document.getElementById("imgallegato").src = "file:///" + input.value;
FileReader works fine in Mozilla, Chrome and IE10+, but with IE9- I should use the code above.
The problem is that input.value returns the path of the selected file and I need to get the base64 in order to send it to the server. I can't do the submit of my form, because this approach needs to re-load my jsp and I have others fields.
Is there someone that could help me to get the byte array from selected file on IE without using canvas element, HTML5 and FileReader library?

POSTing data serverside AND execute javascript code on submitting a form

My goal is to upload some images to a server and provide them with a description.
On clicking an upload button, this is what I want to happen:
1) a javascript function dynamically adds a form to get a description
of the images.
2) on submitting the form:
a) the description entered in the form must be available $_POST['description'] at server side.
b) the images are sent to the server using an XMLHttpRequest
In the code I wrote the description is not available $_POST['description'].
When i remove the check if(!isset($_POST['description'])), the imagefiles are perfectly uploaded.
This is my code:
javascript code
upload.onclick = uploadPrompt;
// dynamically add a form
function uploadPrompt () {
// fileQueue is an array containing all images that need to be uploaded
if (fileQueue.length < 1) {
alert("There are no images available for uploading.");
} else {
var inputDescription = document.createElement("input");
inputDescription.className = "promptInput";
inputDescription.type = "text";
inputDescription.name = "description";
var inputButton = document.createElement("button");
inputButton.id = "promptInputButton";
inputButton.type = "submit";
inputButton.innerHTML = "Start uploading";
var promptForm = document.createElement("form");
promptForm.method = "post";
promptForm.action = "upload.php";
promptForm.onsubmit = uploadQueue;
promptForm.id = "promptForm";
promptForm.appendChild(inputDescription);
promptForm.appendChild(inputButton);
document.body.appendChild(promptForm);
}
}
function uploadQueue(ev) {
ev.preventDefault();
elementToBeRemoved = document.getElementById("promptForm");
elementToBeRemoved.parentElement.removeChild(elementToBeRemoved);
while (fileQueue.length > 0) {
var item = fileQueue.pop();
// item.file is the actual image data
uploadFile(item.file);
}
}
function uploadFile (file) {
if (file) {
var xhr = new XMLHttpRequest();
var fd = new FormData();
fd.append('image',file);
xhr.upload.addEventListener("error", function (ev) {
console.log(ev);
}, false);
xhr.open("POST", "upload.php");
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("X-File-Name", file.name);
xhr.send(fd);
}
}
php code upload.php
<?php
session_start();
if (!isset($_POST['description'])) {
echo "upload:fail\n";
echo "message:No scene was specified";
exit();
}
if (isset($_FILES['image'])) {
if(!move_uploaded_file($_FILES['image']['tmp_name'], "uploads/" . $_POST['description'] . "/" . $_FILES['image']['name'])) {
echo "upload:fail\n";
}
else {
echo "upload:succes\n";
}
exit();
}
exit();
?>
I'd really advise against creating your own asynchronous file upload functionality when there is a plethora of developers who have already programmed the same thing better. Check out these options:
Blueimp's jQuery file uploader
Uploadifive (Uploadify's HTML5 implementation)
I've used these two before and they work very well. For BlueImp, you can use this option to send additional form data:
$('#fileupload').fileupload({
formData: $('.some_form').serialize()
});
The above captures a form and serializes its inputs. Alternatively, you can populate an array or object using specific values (i.e. from specific elements in your DOM):
var array = new Array();
$('.description').each(function() {
array[this.id] = this.value;
});
You'd use IDs to link your files and descriptions.

Categories

Resources