jQuery mobile- display a delete icon when upload a picture - image

I have to display a delete icon (png file) when the user upload a picture.
I use the following code for display the picture
$(document).ready(function(){
var $file = $('input[type=file]');
$('a.ui-icon-camera').click(function () {
$file.trigger("click");
});
$file.change(function () {
var file = $file[0].files[0];
$(this).fileExif(someCallback);
displayAsImage3(file,"showPic");
});
});
function displayAsImage3(file, containerid) {
if (typeof FileReader !== "undefined") {
var container = document.getElementById(containerid),
img = document.createElement("img"),
reader;
$(img).addClass('smallImg');
$('#'+containerid).empty();
container.appendChild(img);
reader = new FileReader();
reader.onload = (function (theImg) {
return function (evt) {
theImg.src = evt.target.result;
};
}(img));
reader.readAsDataURL(file);
}
}
<div class="hiddenfile"><input type="file" name=${pictureName} accept="image/*" /></div>
<div id="showPic" style="background-color: #E5E5E5; margin: -7% 0; margin-bottom: 1px ">
</div>
How can I append to the image the png icon?

Related

How to refresh only particular portion of page afte I upload Image file

So here I want to get the latest data from dbs after uploading a image. with reloading the whole page again. Instead I want only to refresh the image div to show the latest uploaded image. I guess we can use Ajax for this, but I don't have any expertise in ajax so anyone who can help will be glad.
Thank you :)
Here is my code :-----------
.cshtml file
#for (int i = 0; i < Model.DailyMenuProducts.Count; i++)
{
<li class="list-group-item">
<input asp-for="#Model.DailyMenuProducts[i].IsChecked" type="checkbox" />
<label asp-for="#Model.DailyMenuProducts[i].ProductId"> #Model.DailyMenuProducts[i].ProductName</label>
<input type="hidden" asp-for="#Model.DailyMenuProducts[i].ProductId"/>
<input type="hidden" asp-for="#Model.DailyMenuProducts[i].ProductName" asp-route-productId/>
#if(#Model.DailyMenuProducts[i].DisplayImage != null)
{
<div class="uploadFile float-end" id="div_#Model.DailyMenuProducts[i].ProductId">
<label class="file-label">
<img src="data:image/jpeg;base64,#Model.DailyMenuProducts[i].DisplayImage" width="80" height="80" style="border: 1px solid #000000; cursor:pointer;"/>
</label>
<input asp-for="#Model.DailyMenuProducts[i].ProductImage" asp-for-ProductId="#Model.DailyMenuProducts[i].ProductId" type="file" class="productImage" id="#Model.DailyMenuProducts[i].ProductId" style="visibility:none; display:none"/>
</div> }
else
{
<div class="uploadFile float-end" id="div_#Model.DailyMenuProducts[i].ProductId">
<a class="file-label btn btn-primary text-white" type="button">
#SharedLocalizer[CashlessCloudConstants.cacheKey_UploadImage]
</a>
<input asp-for="#Model.DailyMenuProducts[i].ProductImage" asp-for-ProductId="#Model.DailyMenuProducts[i].ProductId" type="file" class="productImage" id="#Model.DailyMenuProducts[i].ProductId" style="visibility:none; display:none"/>
</div>
}
</li>
}
.js file
$(".file-label").click(function () {
var parent = $(this).parent();
var target = $(parent).find(".productImage");
$(target).click();
});
$(".uploadFile").on('change', function () {
console.log('new file uploaded')
var imagefiles = event.target.files;
var id = event.target.id;
$(this).find(".imageViewer").attr("src", window.URL.createObjectURL(imagefiles[0]));
var formData = new FormData();
formData.append("productId", id);
formData.append("productImage", imagefiles[0]);
console.log(formData.getAll("productId"));
console.log(formData.getAll("productImage"));
console.log(imagefiles[0])
$.ajax({
url: "/DailyMenuPlanner/AddPhoto",
contentType: false,
processData: false,
data: formData,
method: "POST",
success: function (result) {
window.onbeforeunload = null;
location.reload();
}
});
});
.cs file [Controller Method for AddPhoto]
[HttpPost]
public async Task<IActionResult> AddPhoto([FromForm] DailySelectedProductViewModel dataModel)
{
var userSession = await _userSessionCache.GetUserSessionWithUserIdAsync();
if (dataModel == null)
{
return View("ProductSelection", dataModel);
}
var existing = await _productImageApiService.GetSingleProductImage(userSession.TenantId,dataModel.ProductId);
ProductImages productImage = new ProductImages();
HttpRequest request = HttpContext.Request;
IFormFile file = dataModel.ProductImage;
if (file.Length > 0)
{
using (var memoryStream = new MemoryStream())
{
await file.CopyToAsync(memoryStream);
byte[] imageAsArray = memoryStream.ToArray();
productImage.ProductImage = imageAsArray;
}
productImage.ProductId = dataModel.ProductId;
}
if (existing.Content != null)
{
await _productImageApiService.Delete(userSession.TenantId,dataModel.ProductId);
var createProductPhoto = await _productImageApiService.Create(userSession.TenantId, productImage);
}
else
{
var createProductPhoto = await _productImageApiService.Create(userSession.TenantId, productImage);
}
return Ok();
}

Invalid argument supplied for foreach() using laravel 7 [duplicate]

I have a lot of problem to upload multiple images using AJAX. I write this code:
HTML
<form id="upload" method="post" enctype="multipart/form-data">
<div id="drop" class="drop-area">
<div class="drop-area-label">
Drop image here
</div>
<input type="file" name="file" id="file" multiple/>
</div>
<ul class="gallery-image-list" id="uploads">
<!-- The file uploads will be shown here -->
</ul>
</form>
<div id="listTable"></div>
jQuery/AJAX
$(document).on("change", "input[name^='file']", function(e){
e.preventDefault();
var This = this,
display = $("#uploads");
// list all file data
$.each(This.files, function(i, obj){
// for each image run script asynchronous
(function(i) {
// get data from input file
var file = This.files[i],
name = file.name,
size = file.size,
type = file.type,
lastModified = file.lastModified,
lastModifiedDate = file.lastModifiedDate,
webkitRelativePath = file.webkitRelativePath,
slice = file.slice,
i = i;
// DEBUG
/*
var acc = []
$.each(file, function(index, value) {
acc.push(index + ": " + value);
});
alert(JSON.stringify(acc));
*/
$.ajax({
url:'/ajax/upload.php',
contentType: "multipart/form-data",
data:{
"image":
{
"name":name,
"size":size,
"type":type,
"lastModified":lastModified,
"lastModifiedDate":lastModifiedDate,
"webkitRelativePath":webkitRelativePath,
//"slice":slice,
}
},
type: "POST",
// Custom XMLHttpRequest
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
// Check if upload property exists
if(myXhr.upload)
{
// For handling the progress of the upload
myXhr.upload.addEventListener("progress",progressHandlingFunction, false);
}
return myXhr;
},
cache: false,
success : function(data){
// load ajax data
$("#listTable").append(data);
}
});
// display progress
function progressHandlingFunction(e){
if(e.lengthComputable){
var perc = Math.round((e.loaded / e.total)*100);
perc = ( (perc >= 100) ? 100 : ( (perc <= 0) ? 0 : 0 ) );
$("#progress"+i+" > div")
.attr({"aria-valuenow":perc})
.css("width", perc+"%");
}
}
// display list of files
display.append('<li>'+name+'</li><div class="progress" id="progress'+i+'">'
+'<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;">'
+'</div></div>');
})(i);
});
});
I've tried a various versions and I never succeed to send multiple data through ajax. I have tried in this way what you see above, and now I get only POST informations. I understand why i get POST but I need to send FILES information and I do not know where I'm wrong.
I not work the first time with ajax and often use it for most projects but I have never used to send multiple files and that bothering me now.
Thanks!
Try utilizing json to upload , process file object
html
<div id="drop" class="drop-area ui-widget-header">
<div class="drop-area-label">Drop image here</div>
</div>
<br />
<form id="upload">
<input type="file" name="file" id="file" multiple="true" accepts="image/*" />
<ul class="gallery-image-list" id="uploads">
<!-- The file uploads will be shown here -->
</ul>
</form>
<div id="listTable"></div>
css
#uploads {
display:block;
position:relative;
}
#uploads li {
list-style:none;
}
#drop {
width: 90%;
height: 100px;
padding: 0.5em;
float: left;
margin: 10px;
border: 8px dotted grey;
}
#drop.hover {
border: 8px dotted green;
}
#drop.err {
border: 8px dotted orangered;
}
js
var display = $("#uploads"); // cache `#uploads`, `this` at `$.ajax()`
var droppable = $("#drop")[0]; // cache `#drop` selector
$.ajaxSetup({
context: display,
contentType: "application/json",
dataType: "json",
beforeSend: function (jqxhr, settings) {
// pre-process `file`
var file = JSON.parse(
decodeURIComponent(settings.data.split(/=/)[1])
);
// add `progress` element for each `file`
var progress = $("<progress />", {
"class": "file-" + (!!$("progress").length
? $("progress").length
: "0"),
"min": 0,
"max": 0,
"value": 0,
"data-name": file.name
});
this.append(progress, file.name + "<br />");
jqxhr.name = progress.attr("class");
}
});
var processFiles = function processFiles(event) {
event.preventDefault();
// process `input[type=file]`, `droppable` `file`
var files = event.target.files || event.dataTransfer.files;
var images = $.map(files, function (file, i) {
var reader = new FileReader();
var dfd = new $.Deferred();
reader.onload = function (e) {
dfd.resolveWith(file, [e.target.result])
};
reader.readAsDataURL(new Blob([file], {
"type": file.type
}));
return dfd.then(function (data) {
return $.ajax({
type: "POST",
url: "/echo/json/",
data: {
"file": JSON.stringify({
"file": data,
"name": this.name,
"size": this.size,
"type": this.type
})
},
xhr: function () {
// do `progress` event stuff
var uploads = this.context;
var progress = this.context.find("progress:last");
var xhrUpload = $.ajaxSettings.xhr();
if (xhrUpload.upload) {
xhrUpload.upload.onprogress = function (evt) {
progress.attr({
"max": evt.total,
"value": evt.loaded
})
};
xhrUpload.upload.onloadend = function (evt) {
var progressData = progress.eq(-1);
console.log(progressData.data("name")
+ " upload complete...");
var img = new Image;
$(img).addClass(progressData.eq(-1)
.attr("class"));
img.onload = function () {
if (this.complete) {
console.log(
progressData.data("name")
+ " preview loading..."
);
};
};
uploads.append("<br /><li>", img, "</li><br />");
};
}
return xhrUpload;
}
})
.then(function (data, textStatus, jqxhr) {
console.log(data)
this.find("img[class=" + jqxhr.name + "]")
.attr("src", data.file)
.before("<span>" + data.name + "</span><br />");
return data
}, function (jqxhr, textStatus, errorThrown) {
console.log(errorThrown);
return errorThrown
});
})
});
$.when.apply(display, images).then(function () {
var result = $.makeArray(arguments);
console.log(result.length, "uploads complete");
}, function err(jqxhr, textStatus, errorThrown) {
console.log(jqxhr, textStatus, errorThrown)
})
};
$(document)
.on("change", "input[name^=file]", processFiles);
// process `droppable` events
droppable.ondragover = function () {
$(this).addClass("hover");
return false;
};
droppable.ondragend = function () {
$(this).removeClass("hover")
return false;
};
droppable.ondrop = function (e) {
$(this).removeClass("hover");
var image = Array.prototype.slice.call(e.dataTransfer.files)
.every(function (img, i) {
return /^image/.test(img.type)
});
e.preventDefault();
// if `file`, file type `image` , process `file`
if (!!e.dataTransfer.files.length && image) {
$(this).find(".drop-area-label")
.css("color", "blue")
.html(function (i, html) {
$(this).delay(3000, "msg").queue("msg", function () {
$(this).css("color", "initial").html(html)
}).dequeue("msg");
return "File dropped, processing file upload...";
});
processFiles(e);
} else {
// if dropped `file` _not_ `image`
$(this)
.removeClass("hover")
.addClass("err")
.find(".drop-area-label")
.css("color", "darkred")
.html(function (i, html) {
$(this).delay(3000, "msg").queue("msg", function () {
$(this).css("color", "initial").html(html)
.parent("#drop").removeClass("err")
}).dequeue("msg");
return "Please drop image file...";
});
};
};
php
<?php
if (isset($_POST["file"])) {
// do php stuff
// call `json_encode` on `file` object
$file = json_encode($_POST["file"]);
// return `file` as `json` string
echo $file;
};
jsfiddle http://jsfiddle.net/guest271314/0hm09yqo/

Showing popup on image click

I'm using this code to show images.
The problem is that it is showing popup only for the first image and not the rest.
Images are loaded from database so they all have the same id.
Is that the problem or something else?
Code :
if (ViewBag.ReceptiSearchAll != null)
{
<div class="col-6 col-lg">
#foreach (var images in ViewBag.ReceptiSearchImages)
{
if (images.Image != null)
{
imagePath = images.Image;
}
else
{
imagePath = images.ImageDefault;
}
<div class="card mb-3" style="max-width: 400px;border:none">
<div class="row no-gutters">
<div class="col-md-12">
<img id="imgrec" class="card-img-top" src="data:image;base64,#System.Convert.ToBase64String(imagePath)" alt="Slika recepta" width="250" height="200">
</div>
</div>
</div>
}
</div>
}
<script>
// Get the modal
var modal = document.getElementById("myModal");
// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.getElementById("imgrec");
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function () {
modal.style.display = "block";
modalImg.src = this.src;
captionText.innerHTML = this.alt;
}
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function () {
modal.style.display = "none";
}
</script>
All your images have the same id.
<img id="imgrec" ...
id is meant to be a unique identifier.
var img = document.getElementById("imgrec");
For that reason, only your first image gets this.
img.onclick = function () {
modal.style.display = "block";
modalImg.src = this.src;
captionText.innerHTML = this.alt;
}

How upload an image in nuxt js and laravel 7

I develop an ecommerce application in nuxtjs frontend and laravel backend.But it is difficult to upload image and save it in the database.Can anyone help me solve the problem ?
Here example of Nuxt Or Vuejs image uploader with Laravel API. I left a comment inside the code for you.
First of all, you must make upload.vue component with this content.
<template>
<div class="container">
<label class="custom-file" for="file">
{{files.length ? `(${files.length}) files are selected` : "Choose files"}}
<input #change="handleSelectedFiles" id="file" multiple name="file" ref="fileInput" type="file">
</label>
<!--Show Selected Files-->
<div class="large-12 medium-12 small-12 cell">
<div class="file-listing" v-for="(file, key) in files">{{ file.name }} <span class="remove-file" v-on:click="removeFile( key )">Remove</span></div>
</div>
<!--Submit Button && Progress Bar-->
<div>
<button #click="upload">Start Upload</button>
- Upload progress : {{this.progress}}
</div>
</div>
</template>
<script>
export default {
data() {
return {
files : [],
progress: 0
}
},
computed: {
/*The FormData : Here We Make A Form With Images Data To Submit.*/
form() {
let form = new FormData();
this.files.forEach((file, index) => {
form.append('files[' + index + ']', file);
});
return form;
}
},
methods : {
handleSelectedFiles() {
let selectedFiles = this.$refs.fileInput.files;
for (let i = 0; i < selectedFiles.length; i++) {
/*Check Already Has Been Selected Or Not ...*/
let isFileExists = this.files.find(file => file.type === selectedFiles[i].type && file.name === selectedFiles[i].name && file.size === selectedFiles[i].size && file.lastModified === selectedFiles[i].lastModified);
if (!isFileExists)
this.files.push(selectedFiles[i]);
}
},
removeFile(key) {
this.files.splice(key, 1);
},
upload() {
const config = {
onUploadProgress: (progressEvent) => this.progress = Math.round((progressEvent.loaded * 100) / progressEvent.total)
};
this.$axios.post('host-url/upload-image', this.form, config)
.then(res => {
this.progress = 0;
this.files = [];
console.log(res)
})
.catch(err => console.log(err))
}
}
}
</script>
<style>
.custom-file {
padding: 1.2rem;
border-radius: .8rem;
display: inline-block;
border: 2px dashed #a0a0a0;
}
.custom-file input {
display: none;
}
</style>
After this, we must make an endpoint in Laravel API routes like this:
Route::post('/upload-image', 'UploadController#image');
In the last, Put this codes on upload
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UploadController extends Controller
{
public function image(Request $request)
{
$request->validate([
'files' => ['required', 'array'],
'files.*' => ['required', 'image','min:5','max:5000']
]);
$uploadedFiles = [];
foreach ($request->file('files') as $file) {
$fileName = bcrypt(microtime()) . "." . $file->getClientOriginalExtension();
$file->move('/uploads', $fileName);
array_push($uploadedFiles, "/uploads/{$fileName}");
}
return response($uploadedFiles);
}
}
Attention: Progress in localhost is so fast, then if you want to test it in local upload a file largest than 50 MB.

Cropped image encrypted data not post in codeigniter on live server. Why?

I have a situation where a user select photo and cropped it.After cropping encoded data passed to hidden input has successfully but when posting my form the image data not post.Only blank page shown.
Same code are working fine on local server. But on live server this happened to me.
Let me share my code. Please guide me where i am doing wrong.
$(".gambar").attr("src", "<?php echo base_url().'assets/img/users/defualt.jpg");
var $uploadCrop,
tempFilename,
rawImg,
imageId;
function readFile(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('.upload-demo').addClass('ready');
$('#cropImagePop').modal('show');
rawImg = e.target.result;
}
reader.readAsDataURL(input.files[0]);
}
else {
swal("Sorry - you're browser doesn't support the FileReader API");
}
}
$uploadCrop = $('#upload-demo').croppie({
viewport: {
width: 150,
height: 150,
type: 'circle'
},
boundary: {
width: 265,
height: 265
},
enforceBoundary: false,
enableExif: true,
enableOrientation: true,
orientation: 4,
});
$('#cropImagePop').on('shown.bs.modal', function(){
$uploadCrop.croppie('bind', {
url: rawImg
}).then(function(){
});
});
$('.item-img').on('change', function () {
imageId = $(this).data('id');
tempFilename = $(this).val();
$('#cancelCropBtn').data('id', imageId);
readFile(this); });
$('#cropImageBtn').on('click', function (ev) {
$uploadCrop.croppie('result', {
type: 'canvas',
format: 'jpeg',
size: {width: 150, height: 150}
}).then(function (resp) {
$('#imageEncoder').val(resp);
$('#item-img-output').attr('src', resp);
$('#cropImagePop').modal('hide');
$('#profile_form').submit();
});
});
<form action="<?= base_url().'userController/update_staff_picture' ?>" method="post" enctype="multipart/form-data" id="profile_form">
<input type="hidden" name="imageEncoder" id="imageEncoder">
<label class="cabinet center-block">
<figure>
<img src="" class="gambar img-responsive img-thumbnail img-circle" id="item-img-output" />
<figcaption><i class="fa fa-camera"></i></figcaption>
</figure>
<input type="file" class="item-img file center-block" name="file_photo"/>
</label>
</form>
User Controller
public function update_staff_picture(){
$data = $this->input->post('imageEncoder');
echo "<pre>";
print_r($data);
exit();
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$image_name = date('ymdgis').'.png';
$req['image']=$image_name;
file_put_contents('./assets/img/users/'.$image_name, $data);
$this->db->set($req);
$this->db->where('userID',$userID);
$this->db->update('users');
redirect(base_url().'staff-profile/'.$_POST['userID']);
}

Resources