Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- $.ajax({
- type: "POST",
- timeout: 50000,
- url: url,
- data: dataString,
- success: function (data) {
- alert('success');
- return false;
- }
- });
- 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 + "%");
- };
- //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();
- });
- <div id="progress-wrp">
- <div class="progress-bar"></div>
- <div class="status">0%</div>
- </div>
- #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;
- }
- 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);
- }
- });
- //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
- ));
- }
- <!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>
- <?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";
- }
- ?>
- $.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');
- });
- $("#submit_car").click( function() {
- var formData = new FormData($('#car_cost_form')[0]);
- $.ajax({
- url: 'car_costs.php',
- data: formData,
- async: false,
- contentType: false,
- processData: false,
- cache: false,
- type: 'POST',
- success: function(data)
- {
- },
- }) return false;
- });
- $(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;
- }
- $(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;
- });
- });
- 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"]));
- <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>
- $("#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");
- }
- });
- });
- });
- $(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');
- }
- }
- <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 formData = new FormData();
- formData.append("userfile", fileInputElement.files[0]);
- data.append("myfile", myBlob, "filename.txt");
- Have an iframe on page and have a referencer.
- Form: A processing page AND a target of the FRAME.
- data:image/png;base64,asdfasdfasdfasdfa
- .aftersubmit(function(){
- stopPropigation()// or some other code which would prevent a refresh.
- });
- 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>
- 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
- });
Add Comment
Please, Sign In to add comment