Uploading multiple files and displaying progress bar - javascript

I'm working on a project (in Django) where I have created a page to add data information about a file and then add the file itself.
When 'More datasets' button is clicked, it adds another field to upload another file.
This can be done to attach as many files as the end-user wants in one go.
What I need is to upload all the attached files once 'Upload data-sets' is clicked and individual progress bar should be displayed.
So far, I have run through multiple tutorials but came kinda close using Vitor Freitas's tutorial.
JS code :
$(function(){
/*$("#add_new_dataset").click(function(){
$(".file").click();
});*/
$(".file").fileupload({
dataType: 'json',
sequentialUploads: true, /* Send the files one by one */
start: function(e){ /* When the upload process starts, show the modal */
$("#modal-progress").modal("show");
},
stop: function(e){ /* When the upload progress finalizes, hide the modal */
$("#modal-progress").modal("hide");
},
progressall: function(e, data){ /* Update the progress bar */
var progress = parseInt(data.loaded / data.total * 100, 10),
strProgress = progress + "%";
$(".progress-bar").css({"width": strProgress});
$(".progress-bar").text(strProgress);
},
done: function(e, data){
if(data.result.is_valid){
$("#gallery tbody").prepend(
"<tr><td><a href='" + data.result.url + "'>" + data.result.name + "</a></td></tr>"
);
}
}
})
});
Template code :
<form id="form" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="container-fluid" id="datasets" style="margin: 0px; padding: 0px;">
<div class="row" onfocusin="populateFilename(this);">
<label class="col-md-2">User Name :</label>
<input class="col-md-2" type="text" id="username" name="user_name" value="{{ user.username }}" readonly />
<label class="col-md-2">Data-set :</label>
<input class="col-md-2" type="text" placeholder="Enter dataset" name="dataset" required />
<label class="col-md-2">Creation Date :</label>
<input class="col-md-2" type="date" placeholder="YYYY-MM-DD" name="creation_date" required />
<label class="col-md-2">Beam Line:</label>
<input class="col-md-2" type="text" placeholder="Enter beam line" name="beamline" required />
<label class="col-md-2">Data-set file:</label>
<input class="col-md-2 file" type="file" name="file" data-url="{% url 'add_data_sets' %}" data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}"}' required />
<label class="filename"></label>
<div class="modal fade" id="modal-progress" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Uploading...</h4>
</div>
<div class="modal-body">
<div class="progress">
<div class="progress-bar" role="progressbar" style="width: 0%;">0%</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div style="align: center; margin-top: 5px;">
<div class="container btn-group btn-group-justified btn-group-lg">
<a onmouseup="addRow();" class="btn btn-outline-secondary" style="width: 50%;">More Datasets</a>
<button type="submit" class="btn btn-outline-primary" name="add_new_dataset" id="add_new_dataset">Submit Data-set</button>
</div>
</div>
What should I do? I'm not very good at AJAX but I can't see any code that works to send the data to the server side. Is it so or am I missing something? Kindly ignore my ignorance on the topic and thanks to all in advance.
EDIT :
The JS code has been rewritten based on some of the answers.
document.getElementById('add_new_dataset').onclick = function() {
$(this).preventDefault();
console.log('Files uploading begin');
form_data = new FormData();
const files = document.getElementsByName('file');
let count = 0;
for(let i = 0; i < files.length; i++){
count++;
form_data.append("file", files[i]);
}
$.ajax({
url: "/add_data_sets",
dataType: 'json',
contentType: false,
processData: false,
data: form_data,
type: 'POST',
success: function(files, response, xhr, pd){
$('.file').show();
if(files.status != false){
$('.progress-bar').val('/location/' + files.filename);
var fileData = files.filename;
console.log('Files uploading...');
}
else{
alert(files.filename);
}
},
/*xhrFields: {
onprogress: function(e) {
if(e.lengthComputable) {
let percentCompleted = e.loaded / evt.total;
pBar.style.width = percentComplete;
pBar.innerHTML = percentComplete + "%";
console.log('Percent complete : ' + percentComplete);
}
}
}*/
xhr: function(){
let xhr = $.ajaxSettings.xhr();
xhr.upload.onprogress = function(e) {
let percentCompleted = e.loaded / evt.total * 100;
pBar.style.width = percentComplete;
pBar.innerHTML = percentComplete + "%";
console.log('Percent complete : ' + percentComplete);
};
return xhr;
}
});
//});
};
This is just the upload code block. The sending of the data from client-side to server-side works perfectly but it makes be suspicious as the 'console.log' calls aren't being triggered when the code runs through it. Is it so that the data is, somehow, being submitted normally and this code is doing nothing.
EDIT2 :
A new JS function:
function upload() {
console.log('Upload function begins');
let pBar = document.getElementsByClassName('progress-bar')[0],
progressWindow = document.getElementById('modal-progress'),
formData = new FormData(document.forms.form),
xhr = new XMLHttpRequest(),
percent = 0;
console.log('Form Data created');
// Start upload
xhr.upload.onloadstart = function() {
//$('#modal-progress').hide().fadeIn();
//progressWindow
};
// Track upload progress
xhr.upload.onprogress = function(event) {
percent = parseInt(event.loaded / event.total * 100);
pBar.innerHTML = percent + "%";
pBar.style.width = percent + "%";
//console.log(percent + '% completed');
//console.log('Uploaded event.loaded of event.total');
};
// Report if ends with an error
xhr.upload.onerror = function() {
console.log('An error has occurred')
};
// Track completion: Both successful or not
xhr.upload.onloadend = function() {
//$('#modal-progress').fadeOut().hide();
console.log('Upload complete with or without error ' + xhr.status);
};
// Track progress: Triggered on successful completion
xhr.upload.onload = function() {
console.log('Uploading complete');
progressWindow.hidden = True;
};
xhr.open("POST", "{% url 'add_data_sets' %}", true);
// The 'setRequestHeader' function can only be called when xhr is opened.
//xhr.setRequestHeader('csrfmiddlewaretoken', '{{ csrf_token }}');
//xhr.setRequestHeader('test-info', 'something');
xhr.setRequestHeader('Content-Type', 'application/gzip');
xhr.send(formData);
}
The function works fine now. It sends the data completely fine but on the development server console screen I get this error.
Forbidden (CSRF token missing or incorrect.): /accounts/add_data_set/
[22/Feb/2020 15:36:06] "POST /accounts/add_data_set/ HTTP/1.1" 403 2513
I even checked logged the POST data being send to the server and it does contain the csrf token
<QueryDict: {'csrfmiddlewaretoken': ['WREoIV0aY4B2XyrU7d9Qw8kMwiokXqwWsmbc2QSHX5VQ0EaYjjeuv7PeysMJjecp'], 'user_name': ['rakesh'], 'dataset': ['r'], 'creation_date': ['2020-02-22'], 'beamline': ['r']}>
I'm kind of confused. Is this an issue?

If you have any fileuploader plugin their documentations will have everything, or if you want normal file upload input you can post them by binding file input to form data and then post on action which will manipulate form data and save images, then you can return save image and display, this way you can achieve simple ajax upload.
var form_data = new FormData();
var totalFiles = document.getElementById('file').files.length;
var count = 0;
for (var i = 0; i < totalFiles; i++) {
var file = document.getElementById('file').files[i];
count++;
form_data.append("file", file);
}
$.ajax({
url: "/uploadingaction",
dataType: 'json',
contentType: false,
processData: false,
data: form_data,
type: 'POST',
success: function (files, response, xhr, pd) {
$('yourloaderid').hide();
if (files.status != false) {
$('#displayid').val('/location/' + files.filename);
var filedata = files.filename;
} else {
alert(files.filename);
}
}
})

Related

How to send an image using Ajax with preview? [duplicate]

Can I use the following jQuery code to perform file upload using POST method of an ajax request ?
$.ajax({
type: "POST",
timeout: 50000,
url: url,
data: dataString,
success: function (data) {
alert('success');
return false;
}
});
If it is possible, do I need to fill data part? Is it the correct way? I only POST the file to the server side.
I have been googling around, but what I found was a plugin while in my plan I do not want to use it. At least for the moment.
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.
Iframes is no longer needed for uploading files through ajax. I've recently done it by myself. Check out these pages:
Using HTML5 file uploads with AJAX and jQuery
http://dev.w3.org/2006/webapi/FileAPI/#FileReader-interface
Updated the answer and cleaned it up. Use the getSize function to check size or use getType function to check types.
Added progressbar html and css code.
var Upload = function (file) {
this.file = file;
};
Upload.prototype.getType = function() {
return this.file.type;
};
Upload.prototype.getSize = function() {
return this.file.size;
};
Upload.prototype.getName = function() {
return this.file.name;
};
Upload.prototype.doUpload = function () {
var that = this;
var formData = new FormData();
// add assoc key values, this will be posts values
formData.append("file", this.file, this.getName());
formData.append("upload_file", true);
$.ajax({
type: "POST",
url: "script",
xhr: function () {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
myXhr.upload.addEventListener('progress', that.progressHandling, false);
}
return myXhr;
},
success: function (data) {
// your callback here
},
error: function (error) {
// handle error
},
async: true,
data: formData,
cache: false,
contentType: false,
processData: false,
timeout: 60000
});
};
Upload.prototype.progressHandling = function (event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
var progress_bar_id = "#progress-wrp";
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
// update progressbars classes so it fits your code
$(progress_bar_id + " .progress-bar").css("width", +percent + "%");
$(progress_bar_id + " .status").text(percent + "%");
};
How to use the Upload class
//Change id to your id
$("#ingredient_file").on("change", function (e) {
var file = $(this)[0].files[0];
var upload = new Upload(file);
// maby check size or type here with upload.getSize() and upload.getType()
// execute upload
upload.doUpload();
});
Progressbar html code
<div id="progress-wrp">
<div class="progress-bar"></div>
<div class="status">0%</div>
</div>
Progressbar css code
#progress-wrp {
border: 1px solid #0099CC;
padding: 1px;
position: relative;
height: 30px;
border-radius: 3px;
margin: 10px;
text-align: left;
background: #fff;
box-shadow: inset 1px 3px 6px rgba(0, 0, 0, 0.12);
}
#progress-wrp .progress-bar {
height: 100%;
border-radius: 3px;
background-color: #f39ac7;
width: 0;
box-shadow: inset 1px 1px 10px rgba(0, 0, 0, 0.11);
}
#progress-wrp .status {
top: 3px;
left: 50%;
position: absolute;
display: inline-block;
color: #000000;
}
Ajax post and upload file is possible. I'm using jQuery $.ajax function to load my files. I tried to use the XHR object but could not get results on the server side with PHP.
var formData = new FormData();
formData.append('file', $('#file')[0].files[0]);
$.ajax({
url : 'upload.php',
type : 'POST',
data : formData,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success : function(data) {
console.log(data);
alert(data);
}
});
As you can see, you must create a FormData object, empty or from (serialized? - $('#yourForm').serialize()) existing form, and then attach the input file.
Here is more information:
- How to upload a file using jQuery.ajax and FormData
- Uploading files via jQuery, object FormData is provided and no file name, GET request
For the PHP process you can use something like this:
//print_r($_FILES);
$fileName = $_FILES['file']['name'];
$fileType = $_FILES['file']['type'];
$fileError = $_FILES['file']['error'];
$fileContent = file_get_contents($_FILES['file']['tmp_name']);
if($fileError == UPLOAD_ERR_OK){
//Processes your file here
}else{
switch($fileError){
case UPLOAD_ERR_INI_SIZE:
$message = 'Error al intentar subir un archivo que excede el tamaño permitido.';
break;
case UPLOAD_ERR_FORM_SIZE:
$message = 'Error al intentar subir un archivo que excede el tamaño permitido.';
break;
case UPLOAD_ERR_PARTIAL:
$message = 'Error: no terminó la acción de subir el archivo.';
break;
case UPLOAD_ERR_NO_FILE:
$message = 'Error: ningún archivo fue subido.';
break;
case UPLOAD_ERR_NO_TMP_DIR:
$message = 'Error: servidor no configurado para carga de archivos.';
break;
case UPLOAD_ERR_CANT_WRITE:
$message= 'Error: posible falla al grabar el archivo.';
break;
case UPLOAD_ERR_EXTENSION:
$message = 'Error: carga de archivo no completada.';
break;
default: $message = 'Error: carga de archivo no completada.';
break;
}
echo json_encode(array(
'error' => true,
'message' => $message
));
}
Simple Upload Form
<script>
//form Submit
$("form").submit(function(evt){
evt.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: 'fileUpload',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
enctype: 'multipart/form-data',
processData: false,
success: function (response) {
alert(response);
}
});
return false;
});
</script>
<!--Upload Form-->
<form>
<table>
<tr>
<td colspan="2">File Upload</td>
</tr>
<tr>
<th>Select File </th>
<td><input id="csv" name="csv" type="file" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="submit"/>
</td>
</tr>
</table>
</form>
I'm pretty late for this but I was looking for an ajax based image uploading solution and the answer I was looking for was kinda scattered throughout this post. The solution I settled on involved the FormData object. I assembled a basic form of the code I put together. You can see it demonstrates how to add a custom field to the form with fd.append() as well as how to handle response data when the ajax request is done.
Upload html:
<!DOCTYPE html>
<html>
<head>
<title>Image Upload Form</title>
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
function submitForm() {
console.log("submit event");
var fd = new FormData(document.getElementById("fileinfo"));
fd.append("label", "WEBUPLOAD");
$.ajax({
url: "upload.php",
type: "POST",
data: fd,
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
}).done(function( data ) {
console.log("PHP Output:");
console.log( data );
});
return false;
}
</script>
</head>
<body>
<form method="post" id="fileinfo" name="fileinfo" onsubmit="return submitForm();">
<label>Select a file:</label><br>
<input type="file" name="file" required />
<input type="submit" value="Upload" />
</form>
<div id="output"></div>
</body>
</html>
In case you are working with php here's a way to handle the upload that includes making use of both of the custom fields demonstrated in the above html.
Upload.php
<?php
if ($_POST["label"]) {
$label = $_POST["label"];
}
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 200000)
&& in_array($extension, $allowedExts)) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else {
$filename = $label.$_FILES["file"]["name"];
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("uploads/" . $filename)) {
echo $filename . " already exists. ";
} else {
move_uploaded_file($_FILES["file"]["tmp_name"],
"uploads/" . $filename);
echo "Stored in: " . "uploads/" . $filename;
}
}
} else {
echo "Invalid file";
}
?>
An AJAX upload is indeed possible with XMLHttpRequest(). No iframes necessary. Upload progress can be shown.
For details see: Answer https://stackoverflow.com/a/4943774/873282 to question jQuery Upload Progress and AJAX file upload.
Here's how I got this working:
HTML
<input type="file" id="file">
<button id='process-file-button'>Process</button>
JS
$('#process-file-button').on('click', function (e) {
let files = new FormData(), // you can consider this as 'data bag'
url = 'yourUrl';
files.append('fileName', $('#file')[0].files[0]); // append selected file to the bag named 'file'
$.ajax({
type: 'post',
url: url,
processData: false,
contentType: false,
data: files,
success: function (response) {
console.log(response);
},
error: function (err) {
console.log(err);
}
});
});
PHP
if (isset($_FILES) && !empty($_FILES)) {
$file = $_FILES['fileName'];
$name = $file['name'];
$path = $file['tmp_name'];
// process your file
}
Using pure js it is easier
async function saveFile(inp)
{
let formData = new FormData();
formData.append("file", inp.files[0]);
await fetch('/upload/somedata', {method: "POST", body: formData});
alert('success');
}
<input type="file" onchange="saveFile(this)" >
In server side you can read original file name (and other info) which is automatically included to request.
You do NOT need to set header "Content-Type" to "multipart/form-data" browser will set it automatically
This solutions should work on all major browsers.
Here is more developed snippet with error handling, timeout and additional json sending
async function saveFile(inp)
{
let user = { name:'john', age:34 };
let formData = new FormData();
let photo = inp.files[0];
formData.append("photo", photo);
formData.append("user", JSON.stringify(user));
const ctrl = new AbortController() // timeout
setTimeout(() => ctrl.abort(), 50000);
try {
let r = await fetch('/upload/image',
{method: "POST", body: formData, signal: ctrl.signal});
console.log('HTTP response code:',r.status);
alert('success');
} catch(e) {
console.log('Huston we have problem...:', e);
}
}
<input type="file" onchange="saveFile(this)" >
<br><br>
Before selecting the file Open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>
In case you want to do it like that:
$.upload( form.action, new FormData( myForm))
.progress( function( progressEvent, upload) {
if( progressEvent.lengthComputable) {
var percent = Math.round( progressEvent.loaded * 100 / progressEvent.total) + '%';
if( upload) {
console.log( percent + ' uploaded');
} else {
console.log( percent + ' downloaded');
}
}
})
.done( function() {
console.log( 'Finished upload');
});
than
https://github.com/lgersman/jquery.orangevolt-ampere/blob/master/src/jquery.upload.js
might be your solution.
Use FormData. It works really well :-) ...
var jform = new FormData();
jform.append('user',$('#user').val());
jform.append('image',$('#image').get(0).files[0]); // Here's the important bit
$.ajax({
url: '/your-form-processing-page-url-here',
type: 'POST',
data: jform,
dataType: 'json',
mimeType: 'multipart/form-data', // this too
contentType: false,
cache: false,
processData: false,
success: function(data, status, jqXHR){
alert('Hooray! All is well.');
console.log(data);
console.log(status);
console.log(jqXHR);
},
error: function(jqXHR,status,error){
// Hopefully we should never reach here
console.log(jqXHR);
console.log(status);
console.log(error);
}
});
$("#submit_car").click(function() {
var formData = new FormData($('#car_cost_form')[0]);
$.ajax({
url: 'car_costs.php',
data: formData,
contentType: false,
processData: false,
cache: false,
type: 'POST',
success: function(data) {
// ...
},
});
});
edit: Note contentype and process data
You can simply use this to upload files via Ajax...... submit input cannot be outside form element :)
2019 update:
html
<form class="fr" method='POST' enctype="multipart/form-data"> {% csrf_token %}
<textarea name='text'>
<input name='example_image'>
<button type="submit">
</form>
js
$(document).on('submit', '.fr', function(){
$.ajax({
type: 'post',
url: url, <--- you insert proper URL path to call your views.py function here.
enctype: 'multipart/form-data',
processData: false,
contentType: false,
data: new FormData(this) ,
success: function(data) {
console.log(data);
}
});
return false;
});
views.py
form = ThisForm(request.POST, request.FILES)
if form.is_valid():
text = form.cleaned_data.get("text")
example_image = request.FILES['example_image']
Use a hidden iframe and set your form's target to that iframe's name. This way, when the form is submitted, only the iframe will be refreshed.
Have an event handler registered for the iframe's load event to parse the response.
I have handled these in a simple code. You can download a working demo from here
For your case, these very possible. I will take you step by step how you can upload a file to the server using AJAX jquery.
First let's us create an HTML file to add the following form file element as shown below.
<form action="" id="formContent" method="post" enctype="multipart/form-data" >
<input type="file" name="file" required id="upload">
<button class="submitI" >Upload Image</button>
</form>
Secondly create a jquery.js file and add the following code to handle our file submission to the server
$("#formContent").submit(function(e){
e.preventDefault();
var formdata = new FormData(this);
$.ajax({
url: "ajax_upload_image.php",
type: "POST",
data: formdata,
mimeTypes:"multipart/form-data",
contentType: false,
cache: false,
processData: false,
success: function(){
alert("file successfully submitted");
},error: function(){
alert("okey");
}
});
});
});
There you are done . View more
Using FormData is the way to go as indicated by many answers. here is a bit of code that works great for this purpose. I also agree with the comment of nesting ajax blocks to complete complex circumstances. By including e.PreventDefault(); in my experience makes the code more cross browser compatible.
$('#UploadB1').click(function(e){
e.preventDefault();
if (!fileupload.valid()) {
return false;
}
var myformData = new FormData();
myformData.append('file', $('#uploadFile')[0].files[0]);
$("#UpdateMessage5").html("Uploading file ....");
$("#UpdateMessage5").css("background","url(../include/images/loaderIcon.gif) no-repeat right");
myformData.append('mode', 'fileUpload');
myformData.append('myid', $('#myid').val());
myformData.append('type', $('#fileType').val());
//formData.append('myfile', file, file.name);
$.ajax({
url: 'include/fetch.php',
method: 'post',
processData: false,
contentType: false,
cache: false,
data: myformData,
enctype: 'multipart/form-data',
success: function(response){
$("#UpdateMessage5").html(response); //.delay(2000).hide(1);
$("#UpdateMessage5").css("background","");
console.log("file successfully submitted");
},error: function(){
console.log("not okay");
}
});
});
I have implemented a multiple file select with instant preview and upload after removing unwanted files from preview via ajax.
Detailed documentation can be found here: http://anasthecoder.blogspot.ae/2014/12/multi-file-select-preview-without.html
Demo: http://jsfiddle.net/anas/6v8Kz/7/embedded/result/
jsFiddle: http://jsfiddle.net/anas/6v8Kz/7/
Javascript:
$(document).ready(function(){
$('form').submit(function(ev){
$('.overlay').show();
$(window).scrollTop(0);
return upload_images_selected(ev, ev.target);
})
})
function add_new_file_uploader(addBtn) {
var currentRow = $(addBtn).parent().parent();
var newRow = $(currentRow).clone();
$(newRow).find('.previewImage, .imagePreviewTable').hide();
$(newRow).find('.removeButton').show();
$(newRow).find('table.imagePreviewTable').find('tr').remove();
$(newRow).find('input.multipleImageFileInput').val('');
$(addBtn).parent().parent().parent().append(newRow);
}
function remove_file_uploader(removeBtn) {
$(removeBtn).parent().parent().remove();
}
function show_image_preview(file_selector) {
//files selected using current file selector
var files = file_selector.files;
//Container of image previews
var imageContainer = $(file_selector).next('table.imagePreviewTable');
//Number of images selected
var number_of_images = files.length;
//Build image preview row
var imagePreviewRow = $('<tr class="imagePreviewRow_0"><td valign=top style="width: 510px;"></td>' +
'<td valign=top><input type="button" value="X" title="Remove Image" class="removeImageButton" imageIndex="0" onclick="remove_selected_image(this)" /></td>' +
'</tr> ');
//Add image preview row
$(imageContainer).html(imagePreviewRow);
if (number_of_images > 1) {
for (var i =1; i<number_of_images; i++) {
/**
*Generate class name of the respective image container appending index of selected images,
*sothat we can match images selected and the one which is previewed
*/
var newImagePreviewRow = $(imagePreviewRow).clone().removeClass('imagePreviewRow_0').addClass('imagePreviewRow_'+i);
$(newImagePreviewRow).find('input[type="button"]').attr('imageIndex', i);
$(imageContainer).append(newImagePreviewRow);
}
}
for (var i = 0; i < files.length; i++) {
var file = files[i];
/**
* Allow only images
*/
var imageType = /image.*/;
if (!file.type.match(imageType)) {
continue;
}
/**
* Create an image dom object dynamically
*/
var img = document.createElement("img");
/**
* Get preview area of the image
*/
var preview = $(imageContainer).find('tr.imagePreviewRow_'+i).find('td:first');
/**
* Append preview of selected image to the corresponding container
*/
preview.append(img);
/**
* Set style of appended preview(Can be done via css also)
*/
preview.find('img').addClass('previewImage').css({'max-width': '500px', 'max-height': '500px'});
/**
* Initialize file reader
*/
var reader = new FileReader();
/**
* Onload event of file reader assign target image to the preview
*/
reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
/**
* Initiate read
*/
reader.readAsDataURL(file);
}
/**
* Show preview
*/
$(imageContainer).show();
}
function remove_selected_image(close_button)
{
/**
* Remove this image from preview
*/
var imageIndex = $(close_button).attr('imageindex');
$(close_button).parents('.imagePreviewRow_' + imageIndex).remove();
}
function upload_images_selected(event, formObj)
{
event.preventDefault();
//Get number of images
var imageCount = $('.previewImage').length;
//Get all multi select inputs
var fileInputs = document.querySelectorAll('.multipleImageFileInput');
//Url where the image is to be uploaded
var url= "/upload-directory/";
//Get number of inputs
var number_of_inputs = $(fileInputs).length;
var inputCount = 0;
//Iterate through each file selector input
$(fileInputs).each(function(index, input){
fileList = input.files;
// Create a new FormData object.
var formData = new FormData();
//Extra parameters can be added to the form data object
formData.append('bulk_upload', '1');
formData.append('username', $('input[name="username"]').val());
//Iterate throug each images selected by each file selector and find if the image is present in the preview
for (var i = 0; i < fileList.length; i++) {
if ($(input).next('.imagePreviewTable').find('.imagePreviewRow_'+i).length != 0) {
var file = fileList[i];
// Check the file type.
if (!file.type.match('image.*')) {
continue;
}
// Add the file to the request.
formData.append('image_uploader_multiple[' +(inputCount++)+ ']', file, file.name);
}
}
// Set up the request.
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.onload = function () {
if (xhr.status === 200) {
var jsonResponse = JSON.parse(xhr.responseText);
if (jsonResponse.status == 1) {
$(jsonResponse.file_info).each(function(){
//Iterate through response and find data corresponding to each file uploaded
var uploaded_file_name = this.original;
var saved_file_name = this.target;
var file_name_input = '<input type="hidden" class="image_name" name="image_names[]" value="' +saved_file_name+ '" />';
file_info_container.append(file_name_input);
imageCount--;
})
//Decrement count of inputs to find all images selected by all multi select are uploaded
number_of_inputs--;
if(number_of_inputs == 0) {
//All images selected by each file selector is uploaded
//Do necessary acteion post upload
$('.overlay').hide();
}
} else {
if (typeof jsonResponse.error_field_name != 'undefined') {
//Do appropriate error action
} else {
alert(jsonResponse.message);
}
$('.overlay').hide();
event.preventDefault();
return false;
}
} else {
/*alert('Something went wrong!');*/
$('.overlay').hide();
event.preventDefault();
}
};
xhr.send(formData);
})
return false;
}
Yes you can, just use javascript to get the file, making sure you read the file as a data URL. Parse out the stuff before base64 to actually get the base 64 encoded data and then if you are using php or really any back end language you can decode the base 64 data and save into a file like shown below
Javascript:
var reader = new FileReader();
reader.onloadend = function ()
{
dataToBeSent = reader.result.split("base64,")[1];
$.post(url, {data:dataToBeSent});
}
reader.readAsDataURL(this.files[0]);
PHP:
file_put_contents('my.pdf', base64_decode($_POST["data"]));
Of course you will probably want to do some validation like checking which file type you are dealing with and stuff like that but this is the idea.
To get all your form inputs, including the type="file" you need to use FormData object.
you will be able to see the formData content in the debugger -> network ->Headers after you will submit the form.
var url = "YOUR_URL";
var form = $('#YOUR_FORM_ID')[0];
var formData = new FormData(form);
$.ajax(url, {
method: 'post',
processData: false,
contentType: false,
data: formData
}).done(function(data){
if (data.success){
alert("Files uploaded");
} else {
alert("Error while uploading the files");
}
}).fail(function(data){
console.log(data);
alert("Error while uploading the files");
});
<html>
<head>
<title>Ajax file upload</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function (e) {
$("#uploadimage").on('submit', (function(e) {
e.preventDefault();
$.ajax({
url: "upload.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
alert(data);
}
});
}));
</script>
</head>
<body>
<div class="main">
<h1>Ajax Image Upload</h1><br/>
<hr>
<form id="uploadimage" action="" method="post" enctype="multipart/form-data">
<div id="image_preview"><img id="previewing" src="noimage.png" /></div>
<hr id="line">
<div id="selectImage">
<label>Select Your Image</label><br/>
<input type="file" name="file" id="file" required />
<input type="submit" value="Upload" class="submit" />
</div>
</form>
</div>
</body>
</html>
to upload a file which is submitted by user as a part of form using jquery please follow the below code :
var formData = new FormData();
formData.append("userfile", fileInputElement.files[0]);
Then send the form data object to server.
We can also append a File or Blob directly to the FormData object.
data.append("myfile", myBlob, "filename.txt");
You can use method ajaxSubmit as follow :)
when you select a file that need upload to server, form be submit to server :)
$(document).ready(function () {
var options = {
target: '#output', // target element(s) to be updated with server response
timeout: 30000,
error: function (jqXHR, textStatus) {
$('#output').html('have any error');
return false;
}
},
success: afterSuccess, // post-submit callback
resetForm: true
// reset the form after successful submit
};
$('#idOfInputFile').on('change', function () {
$('#idOfForm').ajaxSubmit(options);
// always return false to prevent standard browser submit and page navigation
return false;
});
});
If you want to upload file using AJAX here is code which you can use for file uploading.
$(document).ready(function() {
var options = {
beforeSubmit: showRequest,
success: showResponse,
dataType: 'json'
};
$('body').delegate('#image','change', function(){
$('#upload').ajaxForm(options).submit();
});
});
function showRequest(formData, jqForm, options) {
$("#validation-errors").hide().empty();
$("#output").css('display','none');
return true;
}
function showResponse(response, statusText, xhr, $form) {
if(response.success == false)
{
var arr = response.errors;
$.each(arr, function(index, value)
{
if (value.length != 0)
{
$("#validation-errors").append('<div class="alert alert-error"><strong>'+ value +'</strong><div>');
}
});
$("#validation-errors").show();
} else {
$("#output").html("<img src='"+response.file+"' />");
$("#output").css('display','block');
}
}
Here is the HTML for Upload the file
<form class="form-horizontal" id="upload" enctype="multipart/form-data" method="post" action="upload/image'" autocomplete="off">
<input type="file" name="image" id="image" />
</form>
var dataform = new FormData($("#myform")[0]);
//console.log(dataform);
$.ajax({
url: 'url',
type: 'POST',
data: dataform,
async: false,
success: function(res) {
response data;
},
cache: false,
contentType: false,
processData: false
});
<input class="form-control cu-b-border" type="file" id="formFile">
<img id="myImg" src="#">
In js
<script>
var formData = new FormData();
formData.append('file', $('#formFile')[0].files[0]);
$.ajax({
type: "POST",
url: '/GetData/UploadImage',
data: formData,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success: function (data) {
console.log(data);
$('#myImg').attr('src', data);
},
error: function (xhr, ajaxOptions, thrownError) {
}
})
</script>
In controller
public ActionResult UploadImage(HttpPostedFileBase file)
{
string filePath = "";
if (file != null)
{
string path = "/uploads/Temp/";
if (!Directory.Exists(Server.MapPath("~" + path)))
{
Directory.CreateDirectory(Server.MapPath("~" + path));
}
filePath = FileUpload.SaveUploadedFile(file, path);
}
return Json(filePath, JsonRequestBehavior.AllowGet);
}
Here was an idea I was thinking of:
Have an iframe on page and have a referencer.
Have a form in which you move the input type file element to.
Form: A processing page AND a target of the FRAME.
The result will post to the iframe, and then you can just send the fetched data up a level to the image tag you want with something like:
data:image/png;base64,asdfasdfasdfasdfa
and the page loads.
I believe it works for me, and depending you might be able to do something like:
.aftersubmit(function(){
stopPropagation(); // or some other code which would prevent a refresh.
});
This is my code that it works
var formData = new FormData();
var files = $('input[type=file]');
for (var i = 0; i < files.length; i++) {
if (files[i].value == "" || files[i].value == null) {
return false;
}
else {
formData.append(files[i].name, files[i].files[0]);
}
}
var formSerializeArray = $("#Form").serializeArray();
for (var i = 0; i < formSerializeArray.length; i++) {
formData.append(formSerializeArray[i].name, formSerializeArray[i].value)
}
$.ajax({
type: 'POST',
data: formData,
contentType: false,
processData: false,
cache: false,
url: '/Controller/Action',
success: function (response) {
if (response.Success == true) {
return true;
}
else {
return false;
}
},
error: function () {
return false;
},
failure: function () {
return false;
}
});
$("#form-id").submit(function (e) {
e.preventDefault();
});
$("#form-id").submit(function (e) {
var formObj = $(this);
var formURL = formObj.attr("action");
var formData = new FormData(this);
$.ajax({
url: formURL,
type: 'POST',
data: formData,
processData: false,
contentType: false,
async: true,
cache: false,
enctype: "multipart/form-data",
dataType: "json",
success: function (data) {
if (data.success) {
alert(data.success)
}
if (data.error) {
alert(data.error)
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<form class="form-horizontal" id="form-id" action="masterFileController" enctype="multipart/form-data">
<button class="btn-success btn" type="submit" id="btn-save" >Submit</button>
</form>
servlet responce as "out.print("your responce");"

Not being able to upload file using JQuery [duplicate]

Can I use the following jQuery code to perform file upload using POST method of an ajax request ?
$.ajax({
type: "POST",
timeout: 50000,
url: url,
data: dataString,
success: function (data) {
alert('success');
return false;
}
});
If it is possible, do I need to fill data part? Is it the correct way? I only POST the file to the server side.
I have been googling around, but what I found was a plugin while in my plan I do not want to use it. At least for the moment.
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.
Iframes is no longer needed for uploading files through ajax. I've recently done it by myself. Check out these pages:
Using HTML5 file uploads with AJAX and jQuery
http://dev.w3.org/2006/webapi/FileAPI/#FileReader-interface
Updated the answer and cleaned it up. Use the getSize function to check size or use getType function to check types.
Added progressbar html and css code.
var Upload = function (file) {
this.file = file;
};
Upload.prototype.getType = function() {
return this.file.type;
};
Upload.prototype.getSize = function() {
return this.file.size;
};
Upload.prototype.getName = function() {
return this.file.name;
};
Upload.prototype.doUpload = function () {
var that = this;
var formData = new FormData();
// add assoc key values, this will be posts values
formData.append("file", this.file, this.getName());
formData.append("upload_file", true);
$.ajax({
type: "POST",
url: "script",
xhr: function () {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
myXhr.upload.addEventListener('progress', that.progressHandling, false);
}
return myXhr;
},
success: function (data) {
// your callback here
},
error: function (error) {
// handle error
},
async: true,
data: formData,
cache: false,
contentType: false,
processData: false,
timeout: 60000
});
};
Upload.prototype.progressHandling = function (event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
var progress_bar_id = "#progress-wrp";
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
// update progressbars classes so it fits your code
$(progress_bar_id + " .progress-bar").css("width", +percent + "%");
$(progress_bar_id + " .status").text(percent + "%");
};
How to use the Upload class
//Change id to your id
$("#ingredient_file").on("change", function (e) {
var file = $(this)[0].files[0];
var upload = new Upload(file);
// maby check size or type here with upload.getSize() and upload.getType()
// execute upload
upload.doUpload();
});
Progressbar html code
<div id="progress-wrp">
<div class="progress-bar"></div>
<div class="status">0%</div>
</div>
Progressbar css code
#progress-wrp {
border: 1px solid #0099CC;
padding: 1px;
position: relative;
height: 30px;
border-radius: 3px;
margin: 10px;
text-align: left;
background: #fff;
box-shadow: inset 1px 3px 6px rgba(0, 0, 0, 0.12);
}
#progress-wrp .progress-bar {
height: 100%;
border-radius: 3px;
background-color: #f39ac7;
width: 0;
box-shadow: inset 1px 1px 10px rgba(0, 0, 0, 0.11);
}
#progress-wrp .status {
top: 3px;
left: 50%;
position: absolute;
display: inline-block;
color: #000000;
}
Ajax post and upload file is possible. I'm using jQuery $.ajax function to load my files. I tried to use the XHR object but could not get results on the server side with PHP.
var formData = new FormData();
formData.append('file', $('#file')[0].files[0]);
$.ajax({
url : 'upload.php',
type : 'POST',
data : formData,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success : function(data) {
console.log(data);
alert(data);
}
});
As you can see, you must create a FormData object, empty or from (serialized? - $('#yourForm').serialize()) existing form, and then attach the input file.
Here is more information:
- How to upload a file using jQuery.ajax and FormData
- Uploading files via jQuery, object FormData is provided and no file name, GET request
For the PHP process you can use something like this:
//print_r($_FILES);
$fileName = $_FILES['file']['name'];
$fileType = $_FILES['file']['type'];
$fileError = $_FILES['file']['error'];
$fileContent = file_get_contents($_FILES['file']['tmp_name']);
if($fileError == UPLOAD_ERR_OK){
//Processes your file here
}else{
switch($fileError){
case UPLOAD_ERR_INI_SIZE:
$message = 'Error al intentar subir un archivo que excede el tamaño permitido.';
break;
case UPLOAD_ERR_FORM_SIZE:
$message = 'Error al intentar subir un archivo que excede el tamaño permitido.';
break;
case UPLOAD_ERR_PARTIAL:
$message = 'Error: no terminó la acción de subir el archivo.';
break;
case UPLOAD_ERR_NO_FILE:
$message = 'Error: ningún archivo fue subido.';
break;
case UPLOAD_ERR_NO_TMP_DIR:
$message = 'Error: servidor no configurado para carga de archivos.';
break;
case UPLOAD_ERR_CANT_WRITE:
$message= 'Error: posible falla al grabar el archivo.';
break;
case UPLOAD_ERR_EXTENSION:
$message = 'Error: carga de archivo no completada.';
break;
default: $message = 'Error: carga de archivo no completada.';
break;
}
echo json_encode(array(
'error' => true,
'message' => $message
));
}
Simple Upload Form
<script>
//form Submit
$("form").submit(function(evt){
evt.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: 'fileUpload',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
enctype: 'multipart/form-data',
processData: false,
success: function (response) {
alert(response);
}
});
return false;
});
</script>
<!--Upload Form-->
<form>
<table>
<tr>
<td colspan="2">File Upload</td>
</tr>
<tr>
<th>Select File </th>
<td><input id="csv" name="csv" type="file" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="submit"/>
</td>
</tr>
</table>
</form>
I'm pretty late for this but I was looking for an ajax based image uploading solution and the answer I was looking for was kinda scattered throughout this post. The solution I settled on involved the FormData object. I assembled a basic form of the code I put together. You can see it demonstrates how to add a custom field to the form with fd.append() as well as how to handle response data when the ajax request is done.
Upload html:
<!DOCTYPE html>
<html>
<head>
<title>Image Upload Form</title>
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
function submitForm() {
console.log("submit event");
var fd = new FormData(document.getElementById("fileinfo"));
fd.append("label", "WEBUPLOAD");
$.ajax({
url: "upload.php",
type: "POST",
data: fd,
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
}).done(function( data ) {
console.log("PHP Output:");
console.log( data );
});
return false;
}
</script>
</head>
<body>
<form method="post" id="fileinfo" name="fileinfo" onsubmit="return submitForm();">
<label>Select a file:</label><br>
<input type="file" name="file" required />
<input type="submit" value="Upload" />
</form>
<div id="output"></div>
</body>
</html>
In case you are working with php here's a way to handle the upload that includes making use of both of the custom fields demonstrated in the above html.
Upload.php
<?php
if ($_POST["label"]) {
$label = $_POST["label"];
}
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 200000)
&& in_array($extension, $allowedExts)) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else {
$filename = $label.$_FILES["file"]["name"];
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("uploads/" . $filename)) {
echo $filename . " already exists. ";
} else {
move_uploaded_file($_FILES["file"]["tmp_name"],
"uploads/" . $filename);
echo "Stored in: " . "uploads/" . $filename;
}
}
} else {
echo "Invalid file";
}
?>
An AJAX upload is indeed possible with XMLHttpRequest(). No iframes necessary. Upload progress can be shown.
For details see: Answer https://stackoverflow.com/a/4943774/873282 to question jQuery Upload Progress and AJAX file upload.
Here's how I got this working:
HTML
<input type="file" id="file">
<button id='process-file-button'>Process</button>
JS
$('#process-file-button').on('click', function (e) {
let files = new FormData(), // you can consider this as 'data bag'
url = 'yourUrl';
files.append('fileName', $('#file')[0].files[0]); // append selected file to the bag named 'file'
$.ajax({
type: 'post',
url: url,
processData: false,
contentType: false,
data: files,
success: function (response) {
console.log(response);
},
error: function (err) {
console.log(err);
}
});
});
PHP
if (isset($_FILES) && !empty($_FILES)) {
$file = $_FILES['fileName'];
$name = $file['name'];
$path = $file['tmp_name'];
// process your file
}
Using pure js it is easier
async function saveFile(inp)
{
let formData = new FormData();
formData.append("file", inp.files[0]);
await fetch('/upload/somedata', {method: "POST", body: formData});
alert('success');
}
<input type="file" onchange="saveFile(this)" >
In server side you can read original file name (and other info) which is automatically included to request.
You do NOT need to set header "Content-Type" to "multipart/form-data" browser will set it automatically
This solutions should work on all major browsers.
Here is more developed snippet with error handling, timeout and additional json sending
async function saveFile(inp)
{
let user = { name:'john', age:34 };
let formData = new FormData();
let photo = inp.files[0];
formData.append("photo", photo);
formData.append("user", JSON.stringify(user));
const ctrl = new AbortController() // timeout
setTimeout(() => ctrl.abort(), 50000);
try {
let r = await fetch('/upload/image',
{method: "POST", body: formData, signal: ctrl.signal});
console.log('HTTP response code:',r.status);
alert('success');
} catch(e) {
console.log('Huston we have problem...:', e);
}
}
<input type="file" onchange="saveFile(this)" >
<br><br>
Before selecting the file Open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>
In case you want to do it like that:
$.upload( form.action, new FormData( myForm))
.progress( function( progressEvent, upload) {
if( progressEvent.lengthComputable) {
var percent = Math.round( progressEvent.loaded * 100 / progressEvent.total) + '%';
if( upload) {
console.log( percent + ' uploaded');
} else {
console.log( percent + ' downloaded');
}
}
})
.done( function() {
console.log( 'Finished upload');
});
than
https://github.com/lgersman/jquery.orangevolt-ampere/blob/master/src/jquery.upload.js
might be your solution.
Use FormData. It works really well :-) ...
var jform = new FormData();
jform.append('user',$('#user').val());
jform.append('image',$('#image').get(0).files[0]); // Here's the important bit
$.ajax({
url: '/your-form-processing-page-url-here',
type: 'POST',
data: jform,
dataType: 'json',
mimeType: 'multipart/form-data', // this too
contentType: false,
cache: false,
processData: false,
success: function(data, status, jqXHR){
alert('Hooray! All is well.');
console.log(data);
console.log(status);
console.log(jqXHR);
},
error: function(jqXHR,status,error){
// Hopefully we should never reach here
console.log(jqXHR);
console.log(status);
console.log(error);
}
});
$("#submit_car").click(function() {
var formData = new FormData($('#car_cost_form')[0]);
$.ajax({
url: 'car_costs.php',
data: formData,
contentType: false,
processData: false,
cache: false,
type: 'POST',
success: function(data) {
// ...
},
});
});
edit: Note contentype and process data
You can simply use this to upload files via Ajax...... submit input cannot be outside form element :)
2019 update:
html
<form class="fr" method='POST' enctype="multipart/form-data"> {% csrf_token %}
<textarea name='text'>
<input name='example_image'>
<button type="submit">
</form>
js
$(document).on('submit', '.fr', function(){
$.ajax({
type: 'post',
url: url, <--- you insert proper URL path to call your views.py function here.
enctype: 'multipart/form-data',
processData: false,
contentType: false,
data: new FormData(this) ,
success: function(data) {
console.log(data);
}
});
return false;
});
views.py
form = ThisForm(request.POST, request.FILES)
if form.is_valid():
text = form.cleaned_data.get("text")
example_image = request.FILES['example_image']
Use a hidden iframe and set your form's target to that iframe's name. This way, when the form is submitted, only the iframe will be refreshed.
Have an event handler registered for the iframe's load event to parse the response.
I have handled these in a simple code. You can download a working demo from here
For your case, these very possible. I will take you step by step how you can upload a file to the server using AJAX jquery.
First let's us create an HTML file to add the following form file element as shown below.
<form action="" id="formContent" method="post" enctype="multipart/form-data" >
<input type="file" name="file" required id="upload">
<button class="submitI" >Upload Image</button>
</form>
Secondly create a jquery.js file and add the following code to handle our file submission to the server
$("#formContent").submit(function(e){
e.preventDefault();
var formdata = new FormData(this);
$.ajax({
url: "ajax_upload_image.php",
type: "POST",
data: formdata,
mimeTypes:"multipart/form-data",
contentType: false,
cache: false,
processData: false,
success: function(){
alert("file successfully submitted");
},error: function(){
alert("okey");
}
});
});
});
There you are done . View more
Using FormData is the way to go as indicated by many answers. here is a bit of code that works great for this purpose. I also agree with the comment of nesting ajax blocks to complete complex circumstances. By including e.PreventDefault(); in my experience makes the code more cross browser compatible.
$('#UploadB1').click(function(e){
e.preventDefault();
if (!fileupload.valid()) {
return false;
}
var myformData = new FormData();
myformData.append('file', $('#uploadFile')[0].files[0]);
$("#UpdateMessage5").html("Uploading file ....");
$("#UpdateMessage5").css("background","url(../include/images/loaderIcon.gif) no-repeat right");
myformData.append('mode', 'fileUpload');
myformData.append('myid', $('#myid').val());
myformData.append('type', $('#fileType').val());
//formData.append('myfile', file, file.name);
$.ajax({
url: 'include/fetch.php',
method: 'post',
processData: false,
contentType: false,
cache: false,
data: myformData,
enctype: 'multipart/form-data',
success: function(response){
$("#UpdateMessage5").html(response); //.delay(2000).hide(1);
$("#UpdateMessage5").css("background","");
console.log("file successfully submitted");
},error: function(){
console.log("not okay");
}
});
});
I have implemented a multiple file select with instant preview and upload after removing unwanted files from preview via ajax.
Detailed documentation can be found here: http://anasthecoder.blogspot.ae/2014/12/multi-file-select-preview-without.html
Demo: http://jsfiddle.net/anas/6v8Kz/7/embedded/result/
jsFiddle: http://jsfiddle.net/anas/6v8Kz/7/
Javascript:
$(document).ready(function(){
$('form').submit(function(ev){
$('.overlay').show();
$(window).scrollTop(0);
return upload_images_selected(ev, ev.target);
})
})
function add_new_file_uploader(addBtn) {
var currentRow = $(addBtn).parent().parent();
var newRow = $(currentRow).clone();
$(newRow).find('.previewImage, .imagePreviewTable').hide();
$(newRow).find('.removeButton').show();
$(newRow).find('table.imagePreviewTable').find('tr').remove();
$(newRow).find('input.multipleImageFileInput').val('');
$(addBtn).parent().parent().parent().append(newRow);
}
function remove_file_uploader(removeBtn) {
$(removeBtn).parent().parent().remove();
}
function show_image_preview(file_selector) {
//files selected using current file selector
var files = file_selector.files;
//Container of image previews
var imageContainer = $(file_selector).next('table.imagePreviewTable');
//Number of images selected
var number_of_images = files.length;
//Build image preview row
var imagePreviewRow = $('<tr class="imagePreviewRow_0"><td valign=top style="width: 510px;"></td>' +
'<td valign=top><input type="button" value="X" title="Remove Image" class="removeImageButton" imageIndex="0" onclick="remove_selected_image(this)" /></td>' +
'</tr> ');
//Add image preview row
$(imageContainer).html(imagePreviewRow);
if (number_of_images > 1) {
for (var i =1; i<number_of_images; i++) {
/**
*Generate class name of the respective image container appending index of selected images,
*sothat we can match images selected and the one which is previewed
*/
var newImagePreviewRow = $(imagePreviewRow).clone().removeClass('imagePreviewRow_0').addClass('imagePreviewRow_'+i);
$(newImagePreviewRow).find('input[type="button"]').attr('imageIndex', i);
$(imageContainer).append(newImagePreviewRow);
}
}
for (var i = 0; i < files.length; i++) {
var file = files[i];
/**
* Allow only images
*/
var imageType = /image.*/;
if (!file.type.match(imageType)) {
continue;
}
/**
* Create an image dom object dynamically
*/
var img = document.createElement("img");
/**
* Get preview area of the image
*/
var preview = $(imageContainer).find('tr.imagePreviewRow_'+i).find('td:first');
/**
* Append preview of selected image to the corresponding container
*/
preview.append(img);
/**
* Set style of appended preview(Can be done via css also)
*/
preview.find('img').addClass('previewImage').css({'max-width': '500px', 'max-height': '500px'});
/**
* Initialize file reader
*/
var reader = new FileReader();
/**
* Onload event of file reader assign target image to the preview
*/
reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
/**
* Initiate read
*/
reader.readAsDataURL(file);
}
/**
* Show preview
*/
$(imageContainer).show();
}
function remove_selected_image(close_button)
{
/**
* Remove this image from preview
*/
var imageIndex = $(close_button).attr('imageindex');
$(close_button).parents('.imagePreviewRow_' + imageIndex).remove();
}
function upload_images_selected(event, formObj)
{
event.preventDefault();
//Get number of images
var imageCount = $('.previewImage').length;
//Get all multi select inputs
var fileInputs = document.querySelectorAll('.multipleImageFileInput');
//Url where the image is to be uploaded
var url= "/upload-directory/";
//Get number of inputs
var number_of_inputs = $(fileInputs).length;
var inputCount = 0;
//Iterate through each file selector input
$(fileInputs).each(function(index, input){
fileList = input.files;
// Create a new FormData object.
var formData = new FormData();
//Extra parameters can be added to the form data object
formData.append('bulk_upload', '1');
formData.append('username', $('input[name="username"]').val());
//Iterate throug each images selected by each file selector and find if the image is present in the preview
for (var i = 0; i < fileList.length; i++) {
if ($(input).next('.imagePreviewTable').find('.imagePreviewRow_'+i).length != 0) {
var file = fileList[i];
// Check the file type.
if (!file.type.match('image.*')) {
continue;
}
// Add the file to the request.
formData.append('image_uploader_multiple[' +(inputCount++)+ ']', file, file.name);
}
}
// Set up the request.
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.onload = function () {
if (xhr.status === 200) {
var jsonResponse = JSON.parse(xhr.responseText);
if (jsonResponse.status == 1) {
$(jsonResponse.file_info).each(function(){
//Iterate through response and find data corresponding to each file uploaded
var uploaded_file_name = this.original;
var saved_file_name = this.target;
var file_name_input = '<input type="hidden" class="image_name" name="image_names[]" value="' +saved_file_name+ '" />';
file_info_container.append(file_name_input);
imageCount--;
})
//Decrement count of inputs to find all images selected by all multi select are uploaded
number_of_inputs--;
if(number_of_inputs == 0) {
//All images selected by each file selector is uploaded
//Do necessary acteion post upload
$('.overlay').hide();
}
} else {
if (typeof jsonResponse.error_field_name != 'undefined') {
//Do appropriate error action
} else {
alert(jsonResponse.message);
}
$('.overlay').hide();
event.preventDefault();
return false;
}
} else {
/*alert('Something went wrong!');*/
$('.overlay').hide();
event.preventDefault();
}
};
xhr.send(formData);
})
return false;
}
Yes you can, just use javascript to get the file, making sure you read the file as a data URL. Parse out the stuff before base64 to actually get the base 64 encoded data and then if you are using php or really any back end language you can decode the base 64 data and save into a file like shown below
Javascript:
var reader = new FileReader();
reader.onloadend = function ()
{
dataToBeSent = reader.result.split("base64,")[1];
$.post(url, {data:dataToBeSent});
}
reader.readAsDataURL(this.files[0]);
PHP:
file_put_contents('my.pdf', base64_decode($_POST["data"]));
Of course you will probably want to do some validation like checking which file type you are dealing with and stuff like that but this is the idea.
To get all your form inputs, including the type="file" you need to use FormData object.
you will be able to see the formData content in the debugger -> network ->Headers after you will submit the form.
var url = "YOUR_URL";
var form = $('#YOUR_FORM_ID')[0];
var formData = new FormData(form);
$.ajax(url, {
method: 'post',
processData: false,
contentType: false,
data: formData
}).done(function(data){
if (data.success){
alert("Files uploaded");
} else {
alert("Error while uploading the files");
}
}).fail(function(data){
console.log(data);
alert("Error while uploading the files");
});
<html>
<head>
<title>Ajax file upload</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function (e) {
$("#uploadimage").on('submit', (function(e) {
e.preventDefault();
$.ajax({
url: "upload.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
alert(data);
}
});
}));
</script>
</head>
<body>
<div class="main">
<h1>Ajax Image Upload</h1><br/>
<hr>
<form id="uploadimage" action="" method="post" enctype="multipart/form-data">
<div id="image_preview"><img id="previewing" src="noimage.png" /></div>
<hr id="line">
<div id="selectImage">
<label>Select Your Image</label><br/>
<input type="file" name="file" id="file" required />
<input type="submit" value="Upload" class="submit" />
</div>
</form>
</div>
</body>
</html>
to upload a file which is submitted by user as a part of form using jquery please follow the below code :
var formData = new FormData();
formData.append("userfile", fileInputElement.files[0]);
Then send the form data object to server.
We can also append a File or Blob directly to the FormData object.
data.append("myfile", myBlob, "filename.txt");
You can use method ajaxSubmit as follow :)
when you select a file that need upload to server, form be submit to server :)
$(document).ready(function () {
var options = {
target: '#output', // target element(s) to be updated with server response
timeout: 30000,
error: function (jqXHR, textStatus) {
$('#output').html('have any error');
return false;
}
},
success: afterSuccess, // post-submit callback
resetForm: true
// reset the form after successful submit
};
$('#idOfInputFile').on('change', function () {
$('#idOfForm').ajaxSubmit(options);
// always return false to prevent standard browser submit and page navigation
return false;
});
});
If you want to upload file using AJAX here is code which you can use for file uploading.
$(document).ready(function() {
var options = {
beforeSubmit: showRequest,
success: showResponse,
dataType: 'json'
};
$('body').delegate('#image','change', function(){
$('#upload').ajaxForm(options).submit();
});
});
function showRequest(formData, jqForm, options) {
$("#validation-errors").hide().empty();
$("#output").css('display','none');
return true;
}
function showResponse(response, statusText, xhr, $form) {
if(response.success == false)
{
var arr = response.errors;
$.each(arr, function(index, value)
{
if (value.length != 0)
{
$("#validation-errors").append('<div class="alert alert-error"><strong>'+ value +'</strong><div>');
}
});
$("#validation-errors").show();
} else {
$("#output").html("<img src='"+response.file+"' />");
$("#output").css('display','block');
}
}
Here is the HTML for Upload the file
<form class="form-horizontal" id="upload" enctype="multipart/form-data" method="post" action="upload/image'" autocomplete="off">
<input type="file" name="image" id="image" />
</form>
var dataform = new FormData($("#myform")[0]);
//console.log(dataform);
$.ajax({
url: 'url',
type: 'POST',
data: dataform,
async: false,
success: function(res) {
response data;
},
cache: false,
contentType: false,
processData: false
});
<input class="form-control cu-b-border" type="file" id="formFile">
<img id="myImg" src="#">
In js
<script>
var formData = new FormData();
formData.append('file', $('#formFile')[0].files[0]);
$.ajax({
type: "POST",
url: '/GetData/UploadImage',
data: formData,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success: function (data) {
console.log(data);
$('#myImg').attr('src', data);
},
error: function (xhr, ajaxOptions, thrownError) {
}
})
</script>
In controller
public ActionResult UploadImage(HttpPostedFileBase file)
{
string filePath = "";
if (file != null)
{
string path = "/uploads/Temp/";
if (!Directory.Exists(Server.MapPath("~" + path)))
{
Directory.CreateDirectory(Server.MapPath("~" + path));
}
filePath = FileUpload.SaveUploadedFile(file, path);
}
return Json(filePath, JsonRequestBehavior.AllowGet);
}
Here was an idea I was thinking of:
Have an iframe on page and have a referencer.
Have a form in which you move the input type file element to.
Form: A processing page AND a target of the FRAME.
The result will post to the iframe, and then you can just send the fetched data up a level to the image tag you want with something like:
data:image/png;base64,asdfasdfasdfasdfa
and the page loads.
I believe it works for me, and depending you might be able to do something like:
.aftersubmit(function(){
stopPropagation(); // or some other code which would prevent a refresh.
});
This is my code that it works
var formData = new FormData();
var files = $('input[type=file]');
for (var i = 0; i < files.length; i++) {
if (files[i].value == "" || files[i].value == null) {
return false;
}
else {
formData.append(files[i].name, files[i].files[0]);
}
}
var formSerializeArray = $("#Form").serializeArray();
for (var i = 0; i < formSerializeArray.length; i++) {
formData.append(formSerializeArray[i].name, formSerializeArray[i].value)
}
$.ajax({
type: 'POST',
data: formData,
contentType: false,
processData: false,
cache: false,
url: '/Controller/Action',
success: function (response) {
if (response.Success == true) {
return true;
}
else {
return false;
}
},
error: function () {
return false;
},
failure: function () {
return false;
}
});
$("#form-id").submit(function (e) {
e.preventDefault();
});
$("#form-id").submit(function (e) {
var formObj = $(this);
var formURL = formObj.attr("action");
var formData = new FormData(this);
$.ajax({
url: formURL,
type: 'POST',
data: formData,
processData: false,
contentType: false,
async: true,
cache: false,
enctype: "multipart/form-data",
dataType: "json",
success: function (data) {
if (data.success) {
alert(data.success)
}
if (data.error) {
alert(data.error)
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<form class="form-horizontal" id="form-id" action="masterFileController" enctype="multipart/form-data">
<button class="btn-success btn" type="submit" id="btn-save" >Submit</button>
</form>
servlet responce as "out.print("your responce");"

File Upload Progress Bar with Multiple and Different Inputs(MVC)

I searched the internet and found this JavaScript and jQuery template for a file upload progress bar that works 100% fine(given the fact that you only use one form input).
My situation is that I need to pass one file and 4 other inputs like text and select to a Controller Action. The action works fine. My problem is to pass all these values through ajax to the Action whilst maintaining the progress bar functionality.
Action Parameters
[HttpPost]
public ActionResult Add_Attachment_to_Process(int id, int Department_id, HttpPostedFileBase Attachment, string sel_checkTask, string cbx_checkTask = null)
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<form method="post" enctype="multipart/form-data" action="/Processes/Add_Attachment_to_Process" id="myform">
<input type="file" id="media" name="file" />
<div class="input-group mb-3">
<div class="input-group-prepend">
<div class="input-group-text">
<input type="checkbox" aria-label="Checkbox for following text input" id="cbx_checkTask" name="cbx_checkTask">
<span id="span_checkTask">Link Task</span>
</div>
</div>
<select class="form-control" id="sel_checkTask" name="sel_checkTask" style="width : 700px;" disabled>
#foreach (var t in Model.User_Tasks)
{
<option value="#t.Task_Discription">#t.Task_Discription - #t.Key_Terms</option>
}
</select>
</div>
<input id="id" name="id" value="#ViewBag.process_id " />
<input id="Department_id" name="Department_id" value="#ViewBag.Department_id" />
<input type="submit" />
</form>
<div class="progress" style="width:40%">
<div id="uploadprogressbar" class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width:0%">
0%
</div>
</div>
JavaScript
$(document).ready(function () {
$("#myform").on('submit', function (event) {
event.preventDefault();
var formData = new FormData($("#myform")[0]);
$.ajax({
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener('progress', function (e) {
if (e.lengthComputable) {
console.log('Bytes Loaded: ' + e.loaded);
console.log('Total Size: ' + e.total);
console.log('Percentage Uploaded: ' + ((e.loaded / e.total) * 100) + '%');
var percent = Math.round((e.loaded / e.total) * 100);
$("#uploadprogressbar").html(percent + '%');
$("#uploadprogressbar").width(percent + '%');
}
});
return xhr;
},
type: 'POST',
url: '/Processes/Add_Attachment_to_Process',
data: formData,
processData: false,
contentType: false,
success: function () {
alert('File Uploaded');
},
error: function (xhr, status, error) {
var errorMessage = xhr.status + ': ' + xhr.statusText;
alert('Error - ' + errorMessage);
}
});
});
});
AS per the discussion above, try this sort of pattern to better see what values are not being sent
let f = new FormData();
f.append('id', getYouFormValue("id"));
f.append('sel_checkTask', getYouFormValue("sel_checkTask"));
f.append('cbx_checkTask ', getYouFormValue("cbx_checkTask "));
if (form.File) {
f.append('File', getYouFormValue("file"));
}
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: f
}
return fetch(`/Processes/Add_Attachment_to_Process`, requestOptions)
.then(handleResponse)
.then(result => {
//do stuff
});
function handleResponse(response) {
return response.text().then(text => {
const data = text && JSON.parse(text);
if (!response.ok) {
if (response.status === 401) {
console.log('not logged in')
}
const error = (data && data.message) || data.title || response.statusText;
return Promise.reject(error);
}
return data;
});
}
function getYouFormValue(element){
let val = document.getElementById(element);
if(!val){
console.log('empty value');
return null;
}
return val;
}

Upload data and files with AJAX [duplicate]

Can I use the following jQuery code to perform file upload using POST method of an ajax request ?
$.ajax({
type: "POST",
timeout: 50000,
url: url,
data: dataString,
success: function (data) {
alert('success');
return false;
}
});
If it is possible, do I need to fill data part? Is it the correct way? I only POST the file to the server side.
I have been googling around, but what I found was a plugin while in my plan I do not want to use it. At least for the moment.
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.
Iframes is no longer needed for uploading files through ajax. I've recently done it by myself. Check out these pages:
Using HTML5 file uploads with AJAX and jQuery
http://dev.w3.org/2006/webapi/FileAPI/#FileReader-interface
Updated the answer and cleaned it up. Use the getSize function to check size or use getType function to check types.
Added progressbar html and css code.
var Upload = function (file) {
this.file = file;
};
Upload.prototype.getType = function() {
return this.file.type;
};
Upload.prototype.getSize = function() {
return this.file.size;
};
Upload.prototype.getName = function() {
return this.file.name;
};
Upload.prototype.doUpload = function () {
var that = this;
var formData = new FormData();
// add assoc key values, this will be posts values
formData.append("file", this.file, this.getName());
formData.append("upload_file", true);
$.ajax({
type: "POST",
url: "script",
xhr: function () {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
myXhr.upload.addEventListener('progress', that.progressHandling, false);
}
return myXhr;
},
success: function (data) {
// your callback here
},
error: function (error) {
// handle error
},
async: true,
data: formData,
cache: false,
contentType: false,
processData: false,
timeout: 60000
});
};
Upload.prototype.progressHandling = function (event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
var progress_bar_id = "#progress-wrp";
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
// update progressbars classes so it fits your code
$(progress_bar_id + " .progress-bar").css("width", +percent + "%");
$(progress_bar_id + " .status").text(percent + "%");
};
How to use the Upload class
//Change id to your id
$("#ingredient_file").on("change", function (e) {
var file = $(this)[0].files[0];
var upload = new Upload(file);
// maby check size or type here with upload.getSize() and upload.getType()
// execute upload
upload.doUpload();
});
Progressbar html code
<div id="progress-wrp">
<div class="progress-bar"></div>
<div class="status">0%</div>
</div>
Progressbar css code
#progress-wrp {
border: 1px solid #0099CC;
padding: 1px;
position: relative;
height: 30px;
border-radius: 3px;
margin: 10px;
text-align: left;
background: #fff;
box-shadow: inset 1px 3px 6px rgba(0, 0, 0, 0.12);
}
#progress-wrp .progress-bar {
height: 100%;
border-radius: 3px;
background-color: #f39ac7;
width: 0;
box-shadow: inset 1px 1px 10px rgba(0, 0, 0, 0.11);
}
#progress-wrp .status {
top: 3px;
left: 50%;
position: absolute;
display: inline-block;
color: #000000;
}
Ajax post and upload file is possible. I'm using jQuery $.ajax function to load my files. I tried to use the XHR object but could not get results on the server side with PHP.
var formData = new FormData();
formData.append('file', $('#file')[0].files[0]);
$.ajax({
url : 'upload.php',
type : 'POST',
data : formData,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success : function(data) {
console.log(data);
alert(data);
}
});
As you can see, you must create a FormData object, empty or from (serialized? - $('#yourForm').serialize()) existing form, and then attach the input file.
Here is more information:
- How to upload a file using jQuery.ajax and FormData
- Uploading files via jQuery, object FormData is provided and no file name, GET request
For the PHP process you can use something like this:
//print_r($_FILES);
$fileName = $_FILES['file']['name'];
$fileType = $_FILES['file']['type'];
$fileError = $_FILES['file']['error'];
$fileContent = file_get_contents($_FILES['file']['tmp_name']);
if($fileError == UPLOAD_ERR_OK){
//Processes your file here
}else{
switch($fileError){
case UPLOAD_ERR_INI_SIZE:
$message = 'Error al intentar subir un archivo que excede el tamaño permitido.';
break;
case UPLOAD_ERR_FORM_SIZE:
$message = 'Error al intentar subir un archivo que excede el tamaño permitido.';
break;
case UPLOAD_ERR_PARTIAL:
$message = 'Error: no terminó la acción de subir el archivo.';
break;
case UPLOAD_ERR_NO_FILE:
$message = 'Error: ningún archivo fue subido.';
break;
case UPLOAD_ERR_NO_TMP_DIR:
$message = 'Error: servidor no configurado para carga de archivos.';
break;
case UPLOAD_ERR_CANT_WRITE:
$message= 'Error: posible falla al grabar el archivo.';
break;
case UPLOAD_ERR_EXTENSION:
$message = 'Error: carga de archivo no completada.';
break;
default: $message = 'Error: carga de archivo no completada.';
break;
}
echo json_encode(array(
'error' => true,
'message' => $message
));
}
Simple Upload Form
<script>
//form Submit
$("form").submit(function(evt){
evt.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: 'fileUpload',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
enctype: 'multipart/form-data',
processData: false,
success: function (response) {
alert(response);
}
});
return false;
});
</script>
<!--Upload Form-->
<form>
<table>
<tr>
<td colspan="2">File Upload</td>
</tr>
<tr>
<th>Select File </th>
<td><input id="csv" name="csv" type="file" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="submit"/>
</td>
</tr>
</table>
</form>
I'm pretty late for this but I was looking for an ajax based image uploading solution and the answer I was looking for was kinda scattered throughout this post. The solution I settled on involved the FormData object. I assembled a basic form of the code I put together. You can see it demonstrates how to add a custom field to the form with fd.append() as well as how to handle response data when the ajax request is done.
Upload html:
<!DOCTYPE html>
<html>
<head>
<title>Image Upload Form</title>
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
function submitForm() {
console.log("submit event");
var fd = new FormData(document.getElementById("fileinfo"));
fd.append("label", "WEBUPLOAD");
$.ajax({
url: "upload.php",
type: "POST",
data: fd,
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
}).done(function( data ) {
console.log("PHP Output:");
console.log( data );
});
return false;
}
</script>
</head>
<body>
<form method="post" id="fileinfo" name="fileinfo" onsubmit="return submitForm();">
<label>Select a file:</label><br>
<input type="file" name="file" required />
<input type="submit" value="Upload" />
</form>
<div id="output"></div>
</body>
</html>
In case you are working with php here's a way to handle the upload that includes making use of both of the custom fields demonstrated in the above html.
Upload.php
<?php
if ($_POST["label"]) {
$label = $_POST["label"];
}
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 200000)
&& in_array($extension, $allowedExts)) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else {
$filename = $label.$_FILES["file"]["name"];
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("uploads/" . $filename)) {
echo $filename . " already exists. ";
} else {
move_uploaded_file($_FILES["file"]["tmp_name"],
"uploads/" . $filename);
echo "Stored in: " . "uploads/" . $filename;
}
}
} else {
echo "Invalid file";
}
?>
An AJAX upload is indeed possible with XMLHttpRequest(). No iframes necessary. Upload progress can be shown.
For details see: Answer https://stackoverflow.com/a/4943774/873282 to question jQuery Upload Progress and AJAX file upload.
Here's how I got this working:
HTML
<input type="file" id="file">
<button id='process-file-button'>Process</button>
JS
$('#process-file-button').on('click', function (e) {
let files = new FormData(), // you can consider this as 'data bag'
url = 'yourUrl';
files.append('fileName', $('#file')[0].files[0]); // append selected file to the bag named 'file'
$.ajax({
type: 'post',
url: url,
processData: false,
contentType: false,
data: files,
success: function (response) {
console.log(response);
},
error: function (err) {
console.log(err);
}
});
});
PHP
if (isset($_FILES) && !empty($_FILES)) {
$file = $_FILES['fileName'];
$name = $file['name'];
$path = $file['tmp_name'];
// process your file
}
Using pure js it is easier
async function saveFile(inp)
{
let formData = new FormData();
formData.append("file", inp.files[0]);
await fetch('/upload/somedata', {method: "POST", body: formData});
alert('success');
}
<input type="file" onchange="saveFile(this)" >
In server side you can read original file name (and other info) which is automatically included to request.
You do NOT need to set header "Content-Type" to "multipart/form-data" browser will set it automatically
This solutions should work on all major browsers.
Here is more developed snippet with error handling, timeout and additional json sending
async function saveFile(inp)
{
let user = { name:'john', age:34 };
let formData = new FormData();
let photo = inp.files[0];
formData.append("photo", photo);
formData.append("user", JSON.stringify(user));
const ctrl = new AbortController() // timeout
setTimeout(() => ctrl.abort(), 50000);
try {
let r = await fetch('/upload/image',
{method: "POST", body: formData, signal: ctrl.signal});
console.log('HTTP response code:',r.status);
alert('success');
} catch(e) {
console.log('Huston we have problem...:', e);
}
}
<input type="file" onchange="saveFile(this)" >
<br><br>
Before selecting the file Open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>
In case you want to do it like that:
$.upload( form.action, new FormData( myForm))
.progress( function( progressEvent, upload) {
if( progressEvent.lengthComputable) {
var percent = Math.round( progressEvent.loaded * 100 / progressEvent.total) + '%';
if( upload) {
console.log( percent + ' uploaded');
} else {
console.log( percent + ' downloaded');
}
}
})
.done( function() {
console.log( 'Finished upload');
});
than
https://github.com/lgersman/jquery.orangevolt-ampere/blob/master/src/jquery.upload.js
might be your solution.
Use FormData. It works really well :-) ...
var jform = new FormData();
jform.append('user',$('#user').val());
jform.append('image',$('#image').get(0).files[0]); // Here's the important bit
$.ajax({
url: '/your-form-processing-page-url-here',
type: 'POST',
data: jform,
dataType: 'json',
mimeType: 'multipart/form-data', // this too
contentType: false,
cache: false,
processData: false,
success: function(data, status, jqXHR){
alert('Hooray! All is well.');
console.log(data);
console.log(status);
console.log(jqXHR);
},
error: function(jqXHR,status,error){
// Hopefully we should never reach here
console.log(jqXHR);
console.log(status);
console.log(error);
}
});
$("#submit_car").click(function() {
var formData = new FormData($('#car_cost_form')[0]);
$.ajax({
url: 'car_costs.php',
data: formData,
contentType: false,
processData: false,
cache: false,
type: 'POST',
success: function(data) {
// ...
},
});
});
edit: Note contentype and process data
You can simply use this to upload files via Ajax...... submit input cannot be outside form element :)
2019 update:
html
<form class="fr" method='POST' enctype="multipart/form-data"> {% csrf_token %}
<textarea name='text'>
<input name='example_image'>
<button type="submit">
</form>
js
$(document).on('submit', '.fr', function(){
$.ajax({
type: 'post',
url: url, <--- you insert proper URL path to call your views.py function here.
enctype: 'multipart/form-data',
processData: false,
contentType: false,
data: new FormData(this) ,
success: function(data) {
console.log(data);
}
});
return false;
});
views.py
form = ThisForm(request.POST, request.FILES)
if form.is_valid():
text = form.cleaned_data.get("text")
example_image = request.FILES['example_image']
Use a hidden iframe and set your form's target to that iframe's name. This way, when the form is submitted, only the iframe will be refreshed.
Have an event handler registered for the iframe's load event to parse the response.
I have handled these in a simple code. You can download a working demo from here
For your case, these very possible. I will take you step by step how you can upload a file to the server using AJAX jquery.
First let's us create an HTML file to add the following form file element as shown below.
<form action="" id="formContent" method="post" enctype="multipart/form-data" >
<input type="file" name="file" required id="upload">
<button class="submitI" >Upload Image</button>
</form>
Secondly create a jquery.js file and add the following code to handle our file submission to the server
$("#formContent").submit(function(e){
e.preventDefault();
var formdata = new FormData(this);
$.ajax({
url: "ajax_upload_image.php",
type: "POST",
data: formdata,
mimeTypes:"multipart/form-data",
contentType: false,
cache: false,
processData: false,
success: function(){
alert("file successfully submitted");
},error: function(){
alert("okey");
}
});
});
});
There you are done . View more
Using FormData is the way to go as indicated by many answers. here is a bit of code that works great for this purpose. I also agree with the comment of nesting ajax blocks to complete complex circumstances. By including e.PreventDefault(); in my experience makes the code more cross browser compatible.
$('#UploadB1').click(function(e){
e.preventDefault();
if (!fileupload.valid()) {
return false;
}
var myformData = new FormData();
myformData.append('file', $('#uploadFile')[0].files[0]);
$("#UpdateMessage5").html("Uploading file ....");
$("#UpdateMessage5").css("background","url(../include/images/loaderIcon.gif) no-repeat right");
myformData.append('mode', 'fileUpload');
myformData.append('myid', $('#myid').val());
myformData.append('type', $('#fileType').val());
//formData.append('myfile', file, file.name);
$.ajax({
url: 'include/fetch.php',
method: 'post',
processData: false,
contentType: false,
cache: false,
data: myformData,
enctype: 'multipart/form-data',
success: function(response){
$("#UpdateMessage5").html(response); //.delay(2000).hide(1);
$("#UpdateMessage5").css("background","");
console.log("file successfully submitted");
},error: function(){
console.log("not okay");
}
});
});
I have implemented a multiple file select with instant preview and upload after removing unwanted files from preview via ajax.
Detailed documentation can be found here: http://anasthecoder.blogspot.ae/2014/12/multi-file-select-preview-without.html
Demo: http://jsfiddle.net/anas/6v8Kz/7/embedded/result/
jsFiddle: http://jsfiddle.net/anas/6v8Kz/7/
Javascript:
$(document).ready(function(){
$('form').submit(function(ev){
$('.overlay').show();
$(window).scrollTop(0);
return upload_images_selected(ev, ev.target);
})
})
function add_new_file_uploader(addBtn) {
var currentRow = $(addBtn).parent().parent();
var newRow = $(currentRow).clone();
$(newRow).find('.previewImage, .imagePreviewTable').hide();
$(newRow).find('.removeButton').show();
$(newRow).find('table.imagePreviewTable').find('tr').remove();
$(newRow).find('input.multipleImageFileInput').val('');
$(addBtn).parent().parent().parent().append(newRow);
}
function remove_file_uploader(removeBtn) {
$(removeBtn).parent().parent().remove();
}
function show_image_preview(file_selector) {
//files selected using current file selector
var files = file_selector.files;
//Container of image previews
var imageContainer = $(file_selector).next('table.imagePreviewTable');
//Number of images selected
var number_of_images = files.length;
//Build image preview row
var imagePreviewRow = $('<tr class="imagePreviewRow_0"><td valign=top style="width: 510px;"></td>' +
'<td valign=top><input type="button" value="X" title="Remove Image" class="removeImageButton" imageIndex="0" onclick="remove_selected_image(this)" /></td>' +
'</tr> ');
//Add image preview row
$(imageContainer).html(imagePreviewRow);
if (number_of_images > 1) {
for (var i =1; i<number_of_images; i++) {
/**
*Generate class name of the respective image container appending index of selected images,
*sothat we can match images selected and the one which is previewed
*/
var newImagePreviewRow = $(imagePreviewRow).clone().removeClass('imagePreviewRow_0').addClass('imagePreviewRow_'+i);
$(newImagePreviewRow).find('input[type="button"]').attr('imageIndex', i);
$(imageContainer).append(newImagePreviewRow);
}
}
for (var i = 0; i < files.length; i++) {
var file = files[i];
/**
* Allow only images
*/
var imageType = /image.*/;
if (!file.type.match(imageType)) {
continue;
}
/**
* Create an image dom object dynamically
*/
var img = document.createElement("img");
/**
* Get preview area of the image
*/
var preview = $(imageContainer).find('tr.imagePreviewRow_'+i).find('td:first');
/**
* Append preview of selected image to the corresponding container
*/
preview.append(img);
/**
* Set style of appended preview(Can be done via css also)
*/
preview.find('img').addClass('previewImage').css({'max-width': '500px', 'max-height': '500px'});
/**
* Initialize file reader
*/
var reader = new FileReader();
/**
* Onload event of file reader assign target image to the preview
*/
reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
/**
* Initiate read
*/
reader.readAsDataURL(file);
}
/**
* Show preview
*/
$(imageContainer).show();
}
function remove_selected_image(close_button)
{
/**
* Remove this image from preview
*/
var imageIndex = $(close_button).attr('imageindex');
$(close_button).parents('.imagePreviewRow_' + imageIndex).remove();
}
function upload_images_selected(event, formObj)
{
event.preventDefault();
//Get number of images
var imageCount = $('.previewImage').length;
//Get all multi select inputs
var fileInputs = document.querySelectorAll('.multipleImageFileInput');
//Url where the image is to be uploaded
var url= "/upload-directory/";
//Get number of inputs
var number_of_inputs = $(fileInputs).length;
var inputCount = 0;
//Iterate through each file selector input
$(fileInputs).each(function(index, input){
fileList = input.files;
// Create a new FormData object.
var formData = new FormData();
//Extra parameters can be added to the form data object
formData.append('bulk_upload', '1');
formData.append('username', $('input[name="username"]').val());
//Iterate throug each images selected by each file selector and find if the image is present in the preview
for (var i = 0; i < fileList.length; i++) {
if ($(input).next('.imagePreviewTable').find('.imagePreviewRow_'+i).length != 0) {
var file = fileList[i];
// Check the file type.
if (!file.type.match('image.*')) {
continue;
}
// Add the file to the request.
formData.append('image_uploader_multiple[' +(inputCount++)+ ']', file, file.name);
}
}
// Set up the request.
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.onload = function () {
if (xhr.status === 200) {
var jsonResponse = JSON.parse(xhr.responseText);
if (jsonResponse.status == 1) {
$(jsonResponse.file_info).each(function(){
//Iterate through response and find data corresponding to each file uploaded
var uploaded_file_name = this.original;
var saved_file_name = this.target;
var file_name_input = '<input type="hidden" class="image_name" name="image_names[]" value="' +saved_file_name+ '" />';
file_info_container.append(file_name_input);
imageCount--;
})
//Decrement count of inputs to find all images selected by all multi select are uploaded
number_of_inputs--;
if(number_of_inputs == 0) {
//All images selected by each file selector is uploaded
//Do necessary acteion post upload
$('.overlay').hide();
}
} else {
if (typeof jsonResponse.error_field_name != 'undefined') {
//Do appropriate error action
} else {
alert(jsonResponse.message);
}
$('.overlay').hide();
event.preventDefault();
return false;
}
} else {
/*alert('Something went wrong!');*/
$('.overlay').hide();
event.preventDefault();
}
};
xhr.send(formData);
})
return false;
}
Yes you can, just use javascript to get the file, making sure you read the file as a data URL. Parse out the stuff before base64 to actually get the base 64 encoded data and then if you are using php or really any back end language you can decode the base 64 data and save into a file like shown below
Javascript:
var reader = new FileReader();
reader.onloadend = function ()
{
dataToBeSent = reader.result.split("base64,")[1];
$.post(url, {data:dataToBeSent});
}
reader.readAsDataURL(this.files[0]);
PHP:
file_put_contents('my.pdf', base64_decode($_POST["data"]));
Of course you will probably want to do some validation like checking which file type you are dealing with and stuff like that but this is the idea.
To get all your form inputs, including the type="file" you need to use FormData object.
you will be able to see the formData content in the debugger -> network ->Headers after you will submit the form.
var url = "YOUR_URL";
var form = $('#YOUR_FORM_ID')[0];
var formData = new FormData(form);
$.ajax(url, {
method: 'post',
processData: false,
contentType: false,
data: formData
}).done(function(data){
if (data.success){
alert("Files uploaded");
} else {
alert("Error while uploading the files");
}
}).fail(function(data){
console.log(data);
alert("Error while uploading the files");
});
<html>
<head>
<title>Ajax file upload</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function (e) {
$("#uploadimage").on('submit', (function(e) {
e.preventDefault();
$.ajax({
url: "upload.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
alert(data);
}
});
}));
</script>
</head>
<body>
<div class="main">
<h1>Ajax Image Upload</h1><br/>
<hr>
<form id="uploadimage" action="" method="post" enctype="multipart/form-data">
<div id="image_preview"><img id="previewing" src="noimage.png" /></div>
<hr id="line">
<div id="selectImage">
<label>Select Your Image</label><br/>
<input type="file" name="file" id="file" required />
<input type="submit" value="Upload" class="submit" />
</div>
</form>
</div>
</body>
</html>
to upload a file which is submitted by user as a part of form using jquery please follow the below code :
var formData = new FormData();
formData.append("userfile", fileInputElement.files[0]);
Then send the form data object to server.
We can also append a File or Blob directly to the FormData object.
data.append("myfile", myBlob, "filename.txt");
You can use method ajaxSubmit as follow :)
when you select a file that need upload to server, form be submit to server :)
$(document).ready(function () {
var options = {
target: '#output', // target element(s) to be updated with server response
timeout: 30000,
error: function (jqXHR, textStatus) {
$('#output').html('have any error');
return false;
}
},
success: afterSuccess, // post-submit callback
resetForm: true
// reset the form after successful submit
};
$('#idOfInputFile').on('change', function () {
$('#idOfForm').ajaxSubmit(options);
// always return false to prevent standard browser submit and page navigation
return false;
});
});
If you want to upload file using AJAX here is code which you can use for file uploading.
$(document).ready(function() {
var options = {
beforeSubmit: showRequest,
success: showResponse,
dataType: 'json'
};
$('body').delegate('#image','change', function(){
$('#upload').ajaxForm(options).submit();
});
});
function showRequest(formData, jqForm, options) {
$("#validation-errors").hide().empty();
$("#output").css('display','none');
return true;
}
function showResponse(response, statusText, xhr, $form) {
if(response.success == false)
{
var arr = response.errors;
$.each(arr, function(index, value)
{
if (value.length != 0)
{
$("#validation-errors").append('<div class="alert alert-error"><strong>'+ value +'</strong><div>');
}
});
$("#validation-errors").show();
} else {
$("#output").html("<img src='"+response.file+"' />");
$("#output").css('display','block');
}
}
Here is the HTML for Upload the file
<form class="form-horizontal" id="upload" enctype="multipart/form-data" method="post" action="upload/image'" autocomplete="off">
<input type="file" name="image" id="image" />
</form>
var dataform = new FormData($("#myform")[0]);
//console.log(dataform);
$.ajax({
url: 'url',
type: 'POST',
data: dataform,
async: false,
success: function(res) {
response data;
},
cache: false,
contentType: false,
processData: false
});
<input class="form-control cu-b-border" type="file" id="formFile">
<img id="myImg" src="#">
In js
<script>
var formData = new FormData();
formData.append('file', $('#formFile')[0].files[0]);
$.ajax({
type: "POST",
url: '/GetData/UploadImage',
data: formData,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success: function (data) {
console.log(data);
$('#myImg').attr('src', data);
},
error: function (xhr, ajaxOptions, thrownError) {
}
})
</script>
In controller
public ActionResult UploadImage(HttpPostedFileBase file)
{
string filePath = "";
if (file != null)
{
string path = "/uploads/Temp/";
if (!Directory.Exists(Server.MapPath("~" + path)))
{
Directory.CreateDirectory(Server.MapPath("~" + path));
}
filePath = FileUpload.SaveUploadedFile(file, path);
}
return Json(filePath, JsonRequestBehavior.AllowGet);
}
Here was an idea I was thinking of:
Have an iframe on page and have a referencer.
Have a form in which you move the input type file element to.
Form: A processing page AND a target of the FRAME.
The result will post to the iframe, and then you can just send the fetched data up a level to the image tag you want with something like:
data:image/png;base64,asdfasdfasdfasdfa
and the page loads.
I believe it works for me, and depending you might be able to do something like:
.aftersubmit(function(){
stopPropagation(); // or some other code which would prevent a refresh.
});
This is my code that it works
var formData = new FormData();
var files = $('input[type=file]');
for (var i = 0; i < files.length; i++) {
if (files[i].value == "" || files[i].value == null) {
return false;
}
else {
formData.append(files[i].name, files[i].files[0]);
}
}
var formSerializeArray = $("#Form").serializeArray();
for (var i = 0; i < formSerializeArray.length; i++) {
formData.append(formSerializeArray[i].name, formSerializeArray[i].value)
}
$.ajax({
type: 'POST',
data: formData,
contentType: false,
processData: false,
cache: false,
url: '/Controller/Action',
success: function (response) {
if (response.Success == true) {
return true;
}
else {
return false;
}
},
error: function () {
return false;
},
failure: function () {
return false;
}
});
$("#form-id").submit(function (e) {
e.preventDefault();
});
$("#form-id").submit(function (e) {
var formObj = $(this);
var formURL = formObj.attr("action");
var formData = new FormData(this);
$.ajax({
url: formURL,
type: 'POST',
data: formData,
processData: false,
contentType: false,
async: true,
cache: false,
enctype: "multipart/form-data",
dataType: "json",
success: function (data) {
if (data.success) {
alert(data.success)
}
if (data.error) {
alert(data.error)
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<form class="form-horizontal" id="form-id" action="masterFileController" enctype="multipart/form-data">
<button class="btn-success btn" type="submit" id="btn-save" >Submit</button>
</form>
servlet responce as "out.print("your responce");"

jQuery Ajax File Upload

Can I use the following jQuery code to perform file upload using POST method of an ajax request ?
$.ajax({
type: "POST",
timeout: 50000,
url: url,
data: dataString,
success: function (data) {
alert('success');
return false;
}
});
If it is possible, do I need to fill data part? Is it the correct way? I only POST the file to the server side.
I have been googling around, but what I found was a plugin while in my plan I do not want to use it. At least for the moment.
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.
Iframes is no longer needed for uploading files through ajax. I've recently done it by myself. Check out these pages:
Using HTML5 file uploads with AJAX and jQuery
http://dev.w3.org/2006/webapi/FileAPI/#FileReader-interface
Updated the answer and cleaned it up. Use the getSize function to check size or use getType function to check types.
Added progressbar html and css code.
var Upload = function (file) {
this.file = file;
};
Upload.prototype.getType = function() {
return this.file.type;
};
Upload.prototype.getSize = function() {
return this.file.size;
};
Upload.prototype.getName = function() {
return this.file.name;
};
Upload.prototype.doUpload = function () {
var that = this;
var formData = new FormData();
// add assoc key values, this will be posts values
formData.append("file", this.file, this.getName());
formData.append("upload_file", true);
$.ajax({
type: "POST",
url: "script",
xhr: function () {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
myXhr.upload.addEventListener('progress', that.progressHandling, false);
}
return myXhr;
},
success: function (data) {
// your callback here
},
error: function (error) {
// handle error
},
async: true,
data: formData,
cache: false,
contentType: false,
processData: false,
timeout: 60000
});
};
Upload.prototype.progressHandling = function (event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
var progress_bar_id = "#progress-wrp";
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
// update progressbars classes so it fits your code
$(progress_bar_id + " .progress-bar").css("width", +percent + "%");
$(progress_bar_id + " .status").text(percent + "%");
};
How to use the Upload class
//Change id to your id
$("#ingredient_file").on("change", function (e) {
var file = $(this)[0].files[0];
var upload = new Upload(file);
// maby check size or type here with upload.getSize() and upload.getType()
// execute upload
upload.doUpload();
});
Progressbar html code
<div id="progress-wrp">
<div class="progress-bar"></div>
<div class="status">0%</div>
</div>
Progressbar css code
#progress-wrp {
border: 1px solid #0099CC;
padding: 1px;
position: relative;
height: 30px;
border-radius: 3px;
margin: 10px;
text-align: left;
background: #fff;
box-shadow: inset 1px 3px 6px rgba(0, 0, 0, 0.12);
}
#progress-wrp .progress-bar {
height: 100%;
border-radius: 3px;
background-color: #f39ac7;
width: 0;
box-shadow: inset 1px 1px 10px rgba(0, 0, 0, 0.11);
}
#progress-wrp .status {
top: 3px;
left: 50%;
position: absolute;
display: inline-block;
color: #000000;
}
Ajax post and upload file is possible. I'm using jQuery $.ajax function to load my files. I tried to use the XHR object but could not get results on the server side with PHP.
var formData = new FormData();
formData.append('file', $('#file')[0].files[0]);
$.ajax({
url : 'upload.php',
type : 'POST',
data : formData,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success : function(data) {
console.log(data);
alert(data);
}
});
As you can see, you must create a FormData object, empty or from (serialized? - $('#yourForm').serialize()) existing form, and then attach the input file.
Here is more information:
- How to upload a file using jQuery.ajax and FormData
- Uploading files via jQuery, object FormData is provided and no file name, GET request
For the PHP process you can use something like this:
//print_r($_FILES);
$fileName = $_FILES['file']['name'];
$fileType = $_FILES['file']['type'];
$fileError = $_FILES['file']['error'];
$fileContent = file_get_contents($_FILES['file']['tmp_name']);
if($fileError == UPLOAD_ERR_OK){
//Processes your file here
}else{
switch($fileError){
case UPLOAD_ERR_INI_SIZE:
$message = 'Error al intentar subir un archivo que excede el tamaño permitido.';
break;
case UPLOAD_ERR_FORM_SIZE:
$message = 'Error al intentar subir un archivo que excede el tamaño permitido.';
break;
case UPLOAD_ERR_PARTIAL:
$message = 'Error: no terminó la acción de subir el archivo.';
break;
case UPLOAD_ERR_NO_FILE:
$message = 'Error: ningún archivo fue subido.';
break;
case UPLOAD_ERR_NO_TMP_DIR:
$message = 'Error: servidor no configurado para carga de archivos.';
break;
case UPLOAD_ERR_CANT_WRITE:
$message= 'Error: posible falla al grabar el archivo.';
break;
case UPLOAD_ERR_EXTENSION:
$message = 'Error: carga de archivo no completada.';
break;
default: $message = 'Error: carga de archivo no completada.';
break;
}
echo json_encode(array(
'error' => true,
'message' => $message
));
}
Simple Upload Form
<script>
//form Submit
$("form").submit(function(evt){
evt.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: 'fileUpload',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
enctype: 'multipart/form-data',
processData: false,
success: function (response) {
alert(response);
}
});
return false;
});
</script>
<!--Upload Form-->
<form>
<table>
<tr>
<td colspan="2">File Upload</td>
</tr>
<tr>
<th>Select File </th>
<td><input id="csv" name="csv" type="file" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="submit"/>
</td>
</tr>
</table>
</form>
I'm pretty late for this but I was looking for an ajax based image uploading solution and the answer I was looking for was kinda scattered throughout this post. The solution I settled on involved the FormData object. I assembled a basic form of the code I put together. You can see it demonstrates how to add a custom field to the form with fd.append() as well as how to handle response data when the ajax request is done.
Upload html:
<!DOCTYPE html>
<html>
<head>
<title>Image Upload Form</title>
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
function submitForm() {
console.log("submit event");
var fd = new FormData(document.getElementById("fileinfo"));
fd.append("label", "WEBUPLOAD");
$.ajax({
url: "upload.php",
type: "POST",
data: fd,
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
}).done(function( data ) {
console.log("PHP Output:");
console.log( data );
});
return false;
}
</script>
</head>
<body>
<form method="post" id="fileinfo" name="fileinfo" onsubmit="return submitForm();">
<label>Select a file:</label><br>
<input type="file" name="file" required />
<input type="submit" value="Upload" />
</form>
<div id="output"></div>
</body>
</html>
In case you are working with php here's a way to handle the upload that includes making use of both of the custom fields demonstrated in the above html.
Upload.php
<?php
if ($_POST["label"]) {
$label = $_POST["label"];
}
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 200000)
&& in_array($extension, $allowedExts)) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else {
$filename = $label.$_FILES["file"]["name"];
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("uploads/" . $filename)) {
echo $filename . " already exists. ";
} else {
move_uploaded_file($_FILES["file"]["tmp_name"],
"uploads/" . $filename);
echo "Stored in: " . "uploads/" . $filename;
}
}
} else {
echo "Invalid file";
}
?>
An AJAX upload is indeed possible with XMLHttpRequest(). No iframes necessary. Upload progress can be shown.
For details see: Answer https://stackoverflow.com/a/4943774/873282 to question jQuery Upload Progress and AJAX file upload.
Here's how I got this working:
HTML
<input type="file" id="file">
<button id='process-file-button'>Process</button>
JS
$('#process-file-button').on('click', function (e) {
let files = new FormData(), // you can consider this as 'data bag'
url = 'yourUrl';
files.append('fileName', $('#file')[0].files[0]); // append selected file to the bag named 'file'
$.ajax({
type: 'post',
url: url,
processData: false,
contentType: false,
data: files,
success: function (response) {
console.log(response);
},
error: function (err) {
console.log(err);
}
});
});
PHP
if (isset($_FILES) && !empty($_FILES)) {
$file = $_FILES['fileName'];
$name = $file['name'];
$path = $file['tmp_name'];
// process your file
}
Using pure js it is easier
async function saveFile(inp)
{
let formData = new FormData();
formData.append("file", inp.files[0]);
await fetch('/upload/somedata', {method: "POST", body: formData});
alert('success');
}
<input type="file" onchange="saveFile(this)" >
In server side you can read original file name (and other info) which is automatically included to request.
You do NOT need to set header "Content-Type" to "multipart/form-data" browser will set it automatically
This solutions should work on all major browsers.
Here is more developed snippet with error handling, timeout and additional json sending
async function saveFile(inp)
{
let user = { name:'john', age:34 };
let formData = new FormData();
let photo = inp.files[0];
formData.append("photo", photo);
formData.append("user", JSON.stringify(user));
const ctrl = new AbortController() // timeout
setTimeout(() => ctrl.abort(), 50000);
try {
let r = await fetch('/upload/image',
{method: "POST", body: formData, signal: ctrl.signal});
console.log('HTTP response code:',r.status);
alert('success');
} catch(e) {
console.log('Huston we have problem...:', e);
}
}
<input type="file" onchange="saveFile(this)" >
<br><br>
Before selecting the file Open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>
In case you want to do it like that:
$.upload( form.action, new FormData( myForm))
.progress( function( progressEvent, upload) {
if( progressEvent.lengthComputable) {
var percent = Math.round( progressEvent.loaded * 100 / progressEvent.total) + '%';
if( upload) {
console.log( percent + ' uploaded');
} else {
console.log( percent + ' downloaded');
}
}
})
.done( function() {
console.log( 'Finished upload');
});
than
https://github.com/lgersman/jquery.orangevolt-ampere/blob/master/src/jquery.upload.js
might be your solution.
Use FormData. It works really well :-) ...
var jform = new FormData();
jform.append('user',$('#user').val());
jform.append('image',$('#image').get(0).files[0]); // Here's the important bit
$.ajax({
url: '/your-form-processing-page-url-here',
type: 'POST',
data: jform,
dataType: 'json',
mimeType: 'multipart/form-data', // this too
contentType: false,
cache: false,
processData: false,
success: function(data, status, jqXHR){
alert('Hooray! All is well.');
console.log(data);
console.log(status);
console.log(jqXHR);
},
error: function(jqXHR,status,error){
// Hopefully we should never reach here
console.log(jqXHR);
console.log(status);
console.log(error);
}
});
$("#submit_car").click(function() {
var formData = new FormData($('#car_cost_form')[0]);
$.ajax({
url: 'car_costs.php',
data: formData,
contentType: false,
processData: false,
cache: false,
type: 'POST',
success: function(data) {
// ...
},
});
});
edit: Note contentype and process data
You can simply use this to upload files via Ajax...... submit input cannot be outside form element :)
2019 update:
html
<form class="fr" method='POST' enctype="multipart/form-data"> {% csrf_token %}
<textarea name='text'>
<input name='example_image'>
<button type="submit">
</form>
js
$(document).on('submit', '.fr', function(){
$.ajax({
type: 'post',
url: url, <--- you insert proper URL path to call your views.py function here.
enctype: 'multipart/form-data',
processData: false,
contentType: false,
data: new FormData(this) ,
success: function(data) {
console.log(data);
}
});
return false;
});
views.py
form = ThisForm(request.POST, request.FILES)
if form.is_valid():
text = form.cleaned_data.get("text")
example_image = request.FILES['example_image']
Use a hidden iframe and set your form's target to that iframe's name. This way, when the form is submitted, only the iframe will be refreshed.
Have an event handler registered for the iframe's load event to parse the response.
I have handled these in a simple code. You can download a working demo from here
For your case, these very possible. I will take you step by step how you can upload a file to the server using AJAX jquery.
First let's us create an HTML file to add the following form file element as shown below.
<form action="" id="formContent" method="post" enctype="multipart/form-data" >
<input type="file" name="file" required id="upload">
<button class="submitI" >Upload Image</button>
</form>
Secondly create a jquery.js file and add the following code to handle our file submission to the server
$("#formContent").submit(function(e){
e.preventDefault();
var formdata = new FormData(this);
$.ajax({
url: "ajax_upload_image.php",
type: "POST",
data: formdata,
mimeTypes:"multipart/form-data",
contentType: false,
cache: false,
processData: false,
success: function(){
alert("file successfully submitted");
},error: function(){
alert("okey");
}
});
});
});
There you are done . View more
Using FormData is the way to go as indicated by many answers. here is a bit of code that works great for this purpose. I also agree with the comment of nesting ajax blocks to complete complex circumstances. By including e.PreventDefault(); in my experience makes the code more cross browser compatible.
$('#UploadB1').click(function(e){
e.preventDefault();
if (!fileupload.valid()) {
return false;
}
var myformData = new FormData();
myformData.append('file', $('#uploadFile')[0].files[0]);
$("#UpdateMessage5").html("Uploading file ....");
$("#UpdateMessage5").css("background","url(../include/images/loaderIcon.gif) no-repeat right");
myformData.append('mode', 'fileUpload');
myformData.append('myid', $('#myid').val());
myformData.append('type', $('#fileType').val());
//formData.append('myfile', file, file.name);
$.ajax({
url: 'include/fetch.php',
method: 'post',
processData: false,
contentType: false,
cache: false,
data: myformData,
enctype: 'multipart/form-data',
success: function(response){
$("#UpdateMessage5").html(response); //.delay(2000).hide(1);
$("#UpdateMessage5").css("background","");
console.log("file successfully submitted");
},error: function(){
console.log("not okay");
}
});
});
I have implemented a multiple file select with instant preview and upload after removing unwanted files from preview via ajax.
Detailed documentation can be found here: http://anasthecoder.blogspot.ae/2014/12/multi-file-select-preview-without.html
Demo: http://jsfiddle.net/anas/6v8Kz/7/embedded/result/
jsFiddle: http://jsfiddle.net/anas/6v8Kz/7/
Javascript:
$(document).ready(function(){
$('form').submit(function(ev){
$('.overlay').show();
$(window).scrollTop(0);
return upload_images_selected(ev, ev.target);
})
})
function add_new_file_uploader(addBtn) {
var currentRow = $(addBtn).parent().parent();
var newRow = $(currentRow).clone();
$(newRow).find('.previewImage, .imagePreviewTable').hide();
$(newRow).find('.removeButton').show();
$(newRow).find('table.imagePreviewTable').find('tr').remove();
$(newRow).find('input.multipleImageFileInput').val('');
$(addBtn).parent().parent().parent().append(newRow);
}
function remove_file_uploader(removeBtn) {
$(removeBtn).parent().parent().remove();
}
function show_image_preview(file_selector) {
//files selected using current file selector
var files = file_selector.files;
//Container of image previews
var imageContainer = $(file_selector).next('table.imagePreviewTable');
//Number of images selected
var number_of_images = files.length;
//Build image preview row
var imagePreviewRow = $('<tr class="imagePreviewRow_0"><td valign=top style="width: 510px;"></td>' +
'<td valign=top><input type="button" value="X" title="Remove Image" class="removeImageButton" imageIndex="0" onclick="remove_selected_image(this)" /></td>' +
'</tr> ');
//Add image preview row
$(imageContainer).html(imagePreviewRow);
if (number_of_images > 1) {
for (var i =1; i<number_of_images; i++) {
/**
*Generate class name of the respective image container appending index of selected images,
*sothat we can match images selected and the one which is previewed
*/
var newImagePreviewRow = $(imagePreviewRow).clone().removeClass('imagePreviewRow_0').addClass('imagePreviewRow_'+i);
$(newImagePreviewRow).find('input[type="button"]').attr('imageIndex', i);
$(imageContainer).append(newImagePreviewRow);
}
}
for (var i = 0; i < files.length; i++) {
var file = files[i];
/**
* Allow only images
*/
var imageType = /image.*/;
if (!file.type.match(imageType)) {
continue;
}
/**
* Create an image dom object dynamically
*/
var img = document.createElement("img");
/**
* Get preview area of the image
*/
var preview = $(imageContainer).find('tr.imagePreviewRow_'+i).find('td:first');
/**
* Append preview of selected image to the corresponding container
*/
preview.append(img);
/**
* Set style of appended preview(Can be done via css also)
*/
preview.find('img').addClass('previewImage').css({'max-width': '500px', 'max-height': '500px'});
/**
* Initialize file reader
*/
var reader = new FileReader();
/**
* Onload event of file reader assign target image to the preview
*/
reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
/**
* Initiate read
*/
reader.readAsDataURL(file);
}
/**
* Show preview
*/
$(imageContainer).show();
}
function remove_selected_image(close_button)
{
/**
* Remove this image from preview
*/
var imageIndex = $(close_button).attr('imageindex');
$(close_button).parents('.imagePreviewRow_' + imageIndex).remove();
}
function upload_images_selected(event, formObj)
{
event.preventDefault();
//Get number of images
var imageCount = $('.previewImage').length;
//Get all multi select inputs
var fileInputs = document.querySelectorAll('.multipleImageFileInput');
//Url where the image is to be uploaded
var url= "/upload-directory/";
//Get number of inputs
var number_of_inputs = $(fileInputs).length;
var inputCount = 0;
//Iterate through each file selector input
$(fileInputs).each(function(index, input){
fileList = input.files;
// Create a new FormData object.
var formData = new FormData();
//Extra parameters can be added to the form data object
formData.append('bulk_upload', '1');
formData.append('username', $('input[name="username"]').val());
//Iterate throug each images selected by each file selector and find if the image is present in the preview
for (var i = 0; i < fileList.length; i++) {
if ($(input).next('.imagePreviewTable').find('.imagePreviewRow_'+i).length != 0) {
var file = fileList[i];
// Check the file type.
if (!file.type.match('image.*')) {
continue;
}
// Add the file to the request.
formData.append('image_uploader_multiple[' +(inputCount++)+ ']', file, file.name);
}
}
// Set up the request.
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.onload = function () {
if (xhr.status === 200) {
var jsonResponse = JSON.parse(xhr.responseText);
if (jsonResponse.status == 1) {
$(jsonResponse.file_info).each(function(){
//Iterate through response and find data corresponding to each file uploaded
var uploaded_file_name = this.original;
var saved_file_name = this.target;
var file_name_input = '<input type="hidden" class="image_name" name="image_names[]" value="' +saved_file_name+ '" />';
file_info_container.append(file_name_input);
imageCount--;
})
//Decrement count of inputs to find all images selected by all multi select are uploaded
number_of_inputs--;
if(number_of_inputs == 0) {
//All images selected by each file selector is uploaded
//Do necessary acteion post upload
$('.overlay').hide();
}
} else {
if (typeof jsonResponse.error_field_name != 'undefined') {
//Do appropriate error action
} else {
alert(jsonResponse.message);
}
$('.overlay').hide();
event.preventDefault();
return false;
}
} else {
/*alert('Something went wrong!');*/
$('.overlay').hide();
event.preventDefault();
}
};
xhr.send(formData);
})
return false;
}
Yes you can, just use javascript to get the file, making sure you read the file as a data URL. Parse out the stuff before base64 to actually get the base 64 encoded data and then if you are using php or really any back end language you can decode the base 64 data and save into a file like shown below
Javascript:
var reader = new FileReader();
reader.onloadend = function ()
{
dataToBeSent = reader.result.split("base64,")[1];
$.post(url, {data:dataToBeSent});
}
reader.readAsDataURL(this.files[0]);
PHP:
file_put_contents('my.pdf', base64_decode($_POST["data"]));
Of course you will probably want to do some validation like checking which file type you are dealing with and stuff like that but this is the idea.
To get all your form inputs, including the type="file" you need to use FormData object.
you will be able to see the formData content in the debugger -> network ->Headers after you will submit the form.
var url = "YOUR_URL";
var form = $('#YOUR_FORM_ID')[0];
var formData = new FormData(form);
$.ajax(url, {
method: 'post',
processData: false,
contentType: false,
data: formData
}).done(function(data){
if (data.success){
alert("Files uploaded");
} else {
alert("Error while uploading the files");
}
}).fail(function(data){
console.log(data);
alert("Error while uploading the files");
});
<html>
<head>
<title>Ajax file upload</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function (e) {
$("#uploadimage").on('submit', (function(e) {
e.preventDefault();
$.ajax({
url: "upload.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
alert(data);
}
});
}));
</script>
</head>
<body>
<div class="main">
<h1>Ajax Image Upload</h1><br/>
<hr>
<form id="uploadimage" action="" method="post" enctype="multipart/form-data">
<div id="image_preview"><img id="previewing" src="noimage.png" /></div>
<hr id="line">
<div id="selectImage">
<label>Select Your Image</label><br/>
<input type="file" name="file" id="file" required />
<input type="submit" value="Upload" class="submit" />
</div>
</form>
</div>
</body>
</html>
to upload a file which is submitted by user as a part of form using jquery please follow the below code :
var formData = new FormData();
formData.append("userfile", fileInputElement.files[0]);
Then send the form data object to server.
We can also append a File or Blob directly to the FormData object.
data.append("myfile", myBlob, "filename.txt");
You can use method ajaxSubmit as follow :)
when you select a file that need upload to server, form be submit to server :)
$(document).ready(function () {
var options = {
target: '#output', // target element(s) to be updated with server response
timeout: 30000,
error: function (jqXHR, textStatus) {
$('#output').html('have any error');
return false;
}
},
success: afterSuccess, // post-submit callback
resetForm: true
// reset the form after successful submit
};
$('#idOfInputFile').on('change', function () {
$('#idOfForm').ajaxSubmit(options);
// always return false to prevent standard browser submit and page navigation
return false;
});
});
If you want to upload file using AJAX here is code which you can use for file uploading.
$(document).ready(function() {
var options = {
beforeSubmit: showRequest,
success: showResponse,
dataType: 'json'
};
$('body').delegate('#image','change', function(){
$('#upload').ajaxForm(options).submit();
});
});
function showRequest(formData, jqForm, options) {
$("#validation-errors").hide().empty();
$("#output").css('display','none');
return true;
}
function showResponse(response, statusText, xhr, $form) {
if(response.success == false)
{
var arr = response.errors;
$.each(arr, function(index, value)
{
if (value.length != 0)
{
$("#validation-errors").append('<div class="alert alert-error"><strong>'+ value +'</strong><div>');
}
});
$("#validation-errors").show();
} else {
$("#output").html("<img src='"+response.file+"' />");
$("#output").css('display','block');
}
}
Here is the HTML for Upload the file
<form class="form-horizontal" id="upload" enctype="multipart/form-data" method="post" action="upload/image'" autocomplete="off">
<input type="file" name="image" id="image" />
</form>
var dataform = new FormData($("#myform")[0]);
//console.log(dataform);
$.ajax({
url: 'url',
type: 'POST',
data: dataform,
async: false,
success: function(res) {
response data;
},
cache: false,
contentType: false,
processData: false
});
<input class="form-control cu-b-border" type="file" id="formFile">
<img id="myImg" src="#">
In js
<script>
var formData = new FormData();
formData.append('file', $('#formFile')[0].files[0]);
$.ajax({
type: "POST",
url: '/GetData/UploadImage',
data: formData,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success: function (data) {
console.log(data);
$('#myImg').attr('src', data);
},
error: function (xhr, ajaxOptions, thrownError) {
}
})
</script>
In controller
public ActionResult UploadImage(HttpPostedFileBase file)
{
string filePath = "";
if (file != null)
{
string path = "/uploads/Temp/";
if (!Directory.Exists(Server.MapPath("~" + path)))
{
Directory.CreateDirectory(Server.MapPath("~" + path));
}
filePath = FileUpload.SaveUploadedFile(file, path);
}
return Json(filePath, JsonRequestBehavior.AllowGet);
}
Here was an idea I was thinking of:
Have an iframe on page and have a referencer.
Have a form in which you move the input type file element to.
Form: A processing page AND a target of the FRAME.
The result will post to the iframe, and then you can just send the fetched data up a level to the image tag you want with something like:
data:image/png;base64,asdfasdfasdfasdfa
and the page loads.
I believe it works for me, and depending you might be able to do something like:
.aftersubmit(function(){
stopPropagation(); // or some other code which would prevent a refresh.
});
This is my code that it works
var formData = new FormData();
var files = $('input[type=file]');
for (var i = 0; i < files.length; i++) {
if (files[i].value == "" || files[i].value == null) {
return false;
}
else {
formData.append(files[i].name, files[i].files[0]);
}
}
var formSerializeArray = $("#Form").serializeArray();
for (var i = 0; i < formSerializeArray.length; i++) {
formData.append(formSerializeArray[i].name, formSerializeArray[i].value)
}
$.ajax({
type: 'POST',
data: formData,
contentType: false,
processData: false,
cache: false,
url: '/Controller/Action',
success: function (response) {
if (response.Success == true) {
return true;
}
else {
return false;
}
},
error: function () {
return false;
},
failure: function () {
return false;
}
});
$("#form-id").submit(function (e) {
e.preventDefault();
});
$("#form-id").submit(function (e) {
var formObj = $(this);
var formURL = formObj.attr("action");
var formData = new FormData(this);
$.ajax({
url: formURL,
type: 'POST',
data: formData,
processData: false,
contentType: false,
async: true,
cache: false,
enctype: "multipart/form-data",
dataType: "json",
success: function (data) {
if (data.success) {
alert(data.success)
}
if (data.error) {
alert(data.error)
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<form class="form-horizontal" id="form-id" action="masterFileController" enctype="multipart/form-data">
<button class="btn-success btn" type="submit" id="btn-save" >Submit</button>
</form>
servlet responce as "out.print("your responce");"

Categories

Resources