Upload Image Using Jquery

How to upload an image through jQuery?

For uploading single image its like this

     <html>
<head>
<meta charset="UTF-8">
<title>AJAX image upload with, jQuery</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function (e) {
$('#upload').on('click', function () {
var file_data = $('#file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'http://localhost/ci/index.php/welcome/upload', // point to server-side controller method
dataType: 'text', // what to expect back from the server
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$('#msg').html(response); // display success response from the server
},
error: function (response) {
$('#msg').html(response); // display error response from the server
}
});
});
});
</script>
</head>
<body>
<p id="msg"></p>

<input type="file" id="file" name="file" multiple />
<button id="upload">Upload</button>
</body>
</html>

For multiple images u will have to loop its kinda different

jQuery Ajax File Upload

File upload is not possible through AJAX.

You can upload file, without refreshing page by using IFrame.

You can check further details here.


UPDATE

With XHR2, File upload through AJAX is supported. E.g. through FormData object, but unfortunately it is not supported by all/old browsers.

FormData support starts from following desktop browsers versions.

  • IE 10+
  • Firefox 4.0+
  • Chrome 7+
  • Safari 5+
  • Opera 12+

For more detail, see MDN link.

How to upload an image with jQuery client side and add it to a div?

Here is a working JSFiddle for what you are looking for

function readURL(e) {
if (this.files && this.files[0]) {
var reader = new FileReader();
$(reader).load(function(e) { $('#blah').attr('src', e.target.result); });
reader.readAsDataURL(this.files[0]);
}
}

$("#imgInp").change(readURL);

As a side note, the above solution uses jQuery although it is not required for a working solution, Javascript only :

function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();

reader.onload = function (e) {
document.getElementById('blah').src = e.target.result;
}

reader.readAsDataURL(input.files[0]);
}
}

And the HTML:

<input type='file' id="imgInp" onchange="readURL(this);" />
<img id="blah" src="#" alt="your image" />

function readURL() { // rehide the image and remove its current "src", // this way if the new image doesn't load, // then the image element is "gone" for now $('#blah').attr('src', '').hide(); if (this.files && this.files[0]) {  var reader = new FileReader();  $(reader).load(function(e) {   $('#blah')    // first we set the attribute of "src" thus changing the image link    .attr('src', e.target.result) // this will now call the load event on the image  });  reader.readAsDataURL(this.files[0]); }}
// below makes use of jQuery chaining. This means the same element is returned after each method, so we don't need to call it again$('#blah') // here we first set a "load" event for the image that will cause it change it's height to a set variable // and make it "show" when finished loading .load(function(e) { // $(this) is the jQuery OBJECT of this which is the element we've called on this load method $(this) // note how easy adding css is, just create an object of the css you want to change or a key/value pair of STRINGS .css('height', '200px') // or .css({ height: '200px' }) // now for the next "method" in the chain, we show the image when loaded .show(); // just that simple }) // with the load event set, we now hide the image as it has nothing in it to start with .hide(); // done
$("#imgInp").change(readURL);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><form id="form1" runat="server">        <input type='file' id="imgInp" />        <img id="blah" src="#" alt="your image" />    </form>

Upload image to folder using ajax/jquery

Here is you solution

HTML

<form id="registerForm" method="post" enctype="multipart/form-data">
<input name="archivo" id="archivo" style="width: 70%;" class="btn btn-block" type="file" onchange="PreviewImage(this)" />
<img id="uploadPreview" />
<button type="submit">Submit</button>

Java Script

function PreviewImage() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("image").files[0]);
oFReader.onload = function (oFREvent) {
document.getElementById("uploadPreview").src = oFREvent.target.result;
};
};

//ajax

$("#registerForm").submit(function(event) {
var formData = new FormData($(this)[0]);
if ($(this).valid()) {
$.ajax({
url : '../../class/upload.php',
type : 'POST',
data : formData,
contentType : false,
cache : false,
processData : false,
success: function(e) {alert(e) },
error : function(x, t, m) {},
});
}
});

PHP

<?php
echo "<pre>"; print_r($_FILES);echo "</pre>"; die; //this will show you the file transfered by form.
$categoria = $_POST['categoria'];
$nombre = $_POST['nombre'];
$descripcion = $_POST['descripcion'];
$img = $_POST['archivo'];
$activo = $_FILES['activo'];
$disponible = $_POST['disponible'];
$precio = $_POST['precio'];
$IdCategoria = 0;
$filepath = "";

//Imagen

if($categoria=="Piano") {
$IdCategoria = 1;
$filepath = "../Files/Productos/Piano/".$img;
}

$filetmp = $_FILES['archivo']['tmp_name'];
move_uploaded_file($filetmp, $filepath);

echo $IdCategoria.$nombre.$descripcion.$filepath.$activo.$disponible.$categoria.$precio;

?>

How to upload image using jQuery?

Try this:

HTML:

<input id="pic" type="file" name="pic" />
<button id="upload">Upload</button>

Jquery:

$('#upload').on('click', function() {
var file_data = $('#pic').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);

$.ajax({
url : 'upload.php', // point to server-side PHP script
dataType : 'text', // what to expect back from the PHP script, if anything
cache : false,
contentType : false,
processData : false,
data : form_data,
type : 'post',
success : function(output){
alert(output); // display response from the PHP script, if any
}
});
$('#pic').val(''); /* Clear the file container */
});

Php:

if ( $_FILES['file']['error'] > 0 ){
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']))
{
echo "File Uploaded Successfully";
}
}

This will uload your file to "uploads" folder. And also check for the folder write permission.

How to upload image using ajax in laravel

create.blade.php

@section('content')
<form id="submitform">
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" id="name">
</div>

<div class="form-group">
<label for="photo">Photo</label>
<input type="file" name="photo" id="photo">
</div>


<button class="btn btn-primary" id="submitBtn" type="submit">
<span class="d-none spinner-grow spinner-grow-sm" role="status" aria-hidden="true"></span>
<span class="">Submit</span>
</button>

</form>
@endsection

@push('custom-scripts')
<script src="{{ asset('js/upload.js') }}"></script>
@endpush

upload.js

$(function () {    
$('#submitBtn').on('click', (e) => {
e.preventDefault();
var formData = new FormData();

let name = $("input[name=name]").val();
let _token = $('meta[name="csrf-token"]').attr('content');
var photo = $('#photo').prop('files')[0];

formData.append('photo', photo);
formData.append('name', name);

$.ajax({
url: 'api/store',
type: 'POST',
contentType: 'multipart/form-data',
cache: false,
contentType: false,
processData: false,
data: formData,
success: (response) => {
// success
console.log(response);
},
error: (response) => {
console.log(response);
}
});
});

});

Controller

class MyController extends Controller
{
use StoreImageTrait;

public function store(Request $request)
{
$data = $request->all();
$data['photo'] = $this->verifyAndStoreImage($request, 'photo', 'students');
Student::create($data);
return response($data, 200);
}
}

StoreImageTrait

<?php

namespace App\Traits;

use Illuminate\Http\Request;

trait StoreImageTrait
{

public function verifyAndStoreImage(Request $request, $filename = 'image', $directory = 'unknown')
{
if ($request->hasFile($filename)) {
if (!$request->file($filename)->isValid()) {
flash('Invalid image')->error()->important();
return redirect()->back()->withInput();
}
return $request->file($filename)->store('image/' . $directory, 'public');
}
return null;
}
}



Related Topics



Leave a reply



Submit