Guest User

Untitled

a guest
Oct 20th, 2017
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 19.67 KB | None | 0 0
  1. $.ajax({
  2. type: "POST",
  3. timeout: 50000,
  4. url: url,
  5. data: dataString,
  6. success: function (data) {
  7. alert('success');
  8. return false;
  9. }
  10. });
  11.  
  12. var Upload = function (file) {
  13. this.file = file;
  14. };
  15.  
  16. Upload.prototype.getType = function() {
  17. return this.file.type;
  18. };
  19. Upload.prototype.getSize = function() {
  20. return this.file.size;
  21. };
  22. Upload.prototype.getName = function() {
  23. return this.file.name;
  24. };
  25. Upload.prototype.doUpload = function () {
  26. var that = this;
  27. var formData = new FormData();
  28.  
  29. // add assoc key values, this will be posts values
  30. formData.append("file", this.file, this.getName());
  31. formData.append("upload_file", true);
  32.  
  33. $.ajax({
  34. type: "POST",
  35. url: "script",
  36. xhr: function () {
  37. var myXhr = $.ajaxSettings.xhr();
  38. if (myXhr.upload) {
  39. myXhr.upload.addEventListener('progress', that.progressHandling, false);
  40. }
  41. return myXhr;
  42. },
  43. success: function (data) {
  44. // your callback here
  45. },
  46. error: function (error) {
  47. // handle error
  48. },
  49. async: true,
  50. data: formData,
  51. cache: false,
  52. contentType: false,
  53. processData: false,
  54. timeout: 60000
  55. });
  56. };
  57.  
  58. Upload.prototype.progressHandling = function (event) {
  59. var percent = 0;
  60. var position = event.loaded || event.position;
  61. var total = event.total;
  62. var progress_bar_id = "#progress-wrp";
  63. if (event.lengthComputable) {
  64. percent = Math.ceil(position / total * 100);
  65. }
  66. // update progressbars classes so it fits your code
  67. $(progress_bar_id + " .progress-bar").css("width", +percent + "%");
  68. $(progress_bar_id + " .status").text(percent + "%");
  69. };
  70.  
  71. //Change id to your id
  72. $("#ingredient_file").on("change", function (e) {
  73. var file = $(this)[0].files[0];
  74. var upload = new Upload(file);
  75.  
  76. // maby check size or type here with upload.getSize() and upload.getType()
  77.  
  78. // execute upload
  79. upload.doUpload();
  80. });
  81.  
  82. <div id="progress-wrp">
  83. <div class="progress-bar"></div>
  84. <div class="status">0%</div>
  85. </div>
  86.  
  87. #progress-wrp {
  88. border: 1px solid #0099CC;
  89. padding: 1px;
  90. position: relative;
  91. height: 30px;
  92. border-radius: 3px;
  93. margin: 10px;
  94. text-align: left;
  95. background: #fff;
  96. box-shadow: inset 1px 3px 6px rgba(0, 0, 0, 0.12);
  97. }
  98. #progress-wrp .progress-bar{
  99. height: 100%;
  100. border-radius: 3px;
  101. background-color: #f39ac7;
  102. width: 0;
  103. box-shadow: inset 1px 1px 10px rgba(0, 0, 0, 0.11);
  104. }
  105. #progress-wrp .status{
  106. top:3px;
  107. left:50%;
  108. position:absolute;
  109. display:inline-block;
  110. color: #000000;
  111. }
  112.  
  113. var formData = new FormData();
  114. formData.append('file', $('#file')[0].files[0]);
  115.  
  116. $.ajax({
  117. url : 'upload.php',
  118. type : 'POST',
  119. data : formData,
  120. processData: false, // tell jQuery not to process the data
  121. contentType: false, // tell jQuery not to set contentType
  122. success : function(data) {
  123. console.log(data);
  124. alert(data);
  125. }
  126. });
  127.  
  128. //print_r($_FILES);
  129. $fileName = $_FILES['file']['name'];
  130. $fileType = $_FILES['file']['type'];
  131. $fileError = $_FILES['file']['error'];
  132. $fileContent = file_get_contents($_FILES['file']['tmp_name']);
  133.  
  134. if($fileError == UPLOAD_ERR_OK){
  135. //Processes your file here
  136. }else{
  137. switch($fileError){
  138. case UPLOAD_ERR_INI_SIZE:
  139. $message = 'Error al intentar subir un archivo que excede el tamaño permitido.';
  140. break;
  141. case UPLOAD_ERR_FORM_SIZE:
  142. $message = 'Error al intentar subir un archivo que excede el tamaño permitido.';
  143. break;
  144. case UPLOAD_ERR_PARTIAL:
  145. $message = 'Error: no terminó la acción de subir el archivo.';
  146. break;
  147. case UPLOAD_ERR_NO_FILE:
  148. $message = 'Error: ningún archivo fue subido.';
  149. break;
  150. case UPLOAD_ERR_NO_TMP_DIR:
  151. $message = 'Error: servidor no configurado para carga de archivos.';
  152. break;
  153. case UPLOAD_ERR_CANT_WRITE:
  154. $message= 'Error: posible falla al grabar el archivo.';
  155. break;
  156. case UPLOAD_ERR_EXTENSION:
  157. $message = 'Error: carga de archivo no completada.';
  158. break;
  159. default: $message = 'Error: carga de archivo no completada.';
  160. break;
  161. }
  162. echo json_encode(array(
  163. 'error' => true,
  164. 'message' => $message
  165. ));
  166. }
  167.  
  168. <!DOCTYPE html>
  169. <html>
  170. <head>
  171. <title>Image Upload Form</title>
  172. <script src="//code.jquery.com/jquery-1.9.1.js"></script>
  173. <script type="text/javascript">
  174. function submitForm() {
  175. console.log("submit event");
  176. var fd = new FormData(document.getElementById("fileinfo"));
  177. fd.append("label", "WEBUPLOAD");
  178. $.ajax({
  179. url: "upload.php",
  180. type: "POST",
  181. data: fd,
  182. processData: false, // tell jQuery not to process the data
  183. contentType: false // tell jQuery not to set contentType
  184. }).done(function( data ) {
  185. console.log("PHP Output:");
  186. console.log( data );
  187. });
  188. return false;
  189. }
  190. </script>
  191. </head>
  192.  
  193. <body>
  194. <form method="post" id="fileinfo" name="fileinfo" onsubmit="return submitForm();">
  195. <label>Select a file:</label><br>
  196. <input type="file" name="file" required />
  197. <input type="submit" value="Upload" />
  198. </form>
  199. <div id="output"></div>
  200. </body>
  201. </html>
  202.  
  203. <?php
  204. if ($_POST["label"]) {
  205. $label = $_POST["label"];
  206. }
  207. $allowedExts = array("gif", "jpeg", "jpg", "png");
  208. $temp = explode(".", $_FILES["file"]["name"]);
  209. $extension = end($temp);
  210. if ((($_FILES["file"]["type"] == "image/gif")
  211. || ($_FILES["file"]["type"] == "image/jpeg")
  212. || ($_FILES["file"]["type"] == "image/jpg")
  213. || ($_FILES["file"]["type"] == "image/pjpeg")
  214. || ($_FILES["file"]["type"] == "image/x-png")
  215. || ($_FILES["file"]["type"] == "image/png"))
  216. && ($_FILES["file"]["size"] < 200000)
  217. && in_array($extension, $allowedExts)) {
  218. if ($_FILES["file"]["error"] > 0) {
  219. echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
  220. } else {
  221. $filename = $label.$_FILES["file"]["name"];
  222. echo "Upload: " . $_FILES["file"]["name"] . "<br>";
  223. echo "Type: " . $_FILES["file"]["type"] . "<br>";
  224. echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
  225. echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
  226.  
  227. if (file_exists("uploads/" . $filename)) {
  228. echo $filename . " already exists. ";
  229. } else {
  230. move_uploaded_file($_FILES["file"]["tmp_name"],
  231. "uploads/" . $filename);
  232. echo "Stored in: " . "uploads/" . $filename;
  233. }
  234. }
  235. } else {
  236. echo "Invalid file";
  237. }
  238. ?>
  239.  
  240. $.upload( form.action, new FormData( myForm))
  241. .progress( function( progressEvent, upload) {
  242. if( progressEvent.lengthComputable) {
  243. var percent = Math.round( progressEvent.loaded * 100 / progressEvent.total) + '%';
  244. if( upload) {
  245. console.log( percent + ' uploaded');
  246. } else {
  247. console.log( percent + ' downloaded');
  248. }
  249. }
  250. })
  251. .done( function() {
  252. console.log( 'Finished upload');
  253. });
  254.  
  255. $("#submit_car").click( function() {
  256. var formData = new FormData($('#car_cost_form')[0]);
  257. $.ajax({
  258. url: 'car_costs.php',
  259. data: formData,
  260. async: false,
  261. contentType: false,
  262. processData: false,
  263. cache: false,
  264. type: 'POST',
  265. success: function(data)
  266. {
  267. },
  268. }) return false;
  269. });
  270.  
  271. $(document).ready(function(){
  272. $('form').submit(function(ev){
  273. $('.overlay').show();
  274. $(window).scrollTop(0);
  275. return upload_images_selected(ev, ev.target);
  276. })
  277. })
  278. function add_new_file_uploader(addBtn) {
  279. var currentRow = $(addBtn).parent().parent();
  280. var newRow = $(currentRow).clone();
  281. $(newRow).find('.previewImage, .imagePreviewTable').hide();
  282. $(newRow).find('.removeButton').show();
  283. $(newRow).find('table.imagePreviewTable').find('tr').remove();
  284. $(newRow).find('input.multipleImageFileInput').val('');
  285. $(addBtn).parent().parent().parent().append(newRow);
  286. }
  287.  
  288. function remove_file_uploader(removeBtn) {
  289. $(removeBtn).parent().parent().remove();
  290. }
  291.  
  292. function show_image_preview(file_selector) {
  293. //files selected using current file selector
  294. var files = file_selector.files;
  295. //Container of image previews
  296. var imageContainer = $(file_selector).next('table.imagePreviewTable');
  297. //Number of images selected
  298. var number_of_images = files.length;
  299. //Build image preview row
  300. var imagePreviewRow = $('<tr class="imagePreviewRow_0"><td valign=top style="width: 510px;"></td>' +
  301. '<td valign=top><input type="button" value="X" title="Remove Image" class="removeImageButton" imageIndex="0" onclick="remove_selected_image(this)" /></td>' +
  302. '</tr> ');
  303. //Add image preview row
  304. $(imageContainer).html(imagePreviewRow);
  305. if (number_of_images > 1) {
  306. for (var i =1; i<number_of_images; i++) {
  307. /**
  308. *Generate class name of the respective image container appending index of selected images,
  309. *sothat we can match images selected and the one which is previewed
  310. */
  311. var newImagePreviewRow = $(imagePreviewRow).clone().removeClass('imagePreviewRow_0').addClass('imagePreviewRow_'+i);
  312. $(newImagePreviewRow).find('input[type="button"]').attr('imageIndex', i);
  313. $(imageContainer).append(newImagePreviewRow);
  314. }
  315. }
  316. for (var i = 0; i < files.length; i++) {
  317. var file = files[i];
  318. /**
  319. * Allow only images
  320. */
  321. var imageType = /image.*/;
  322. if (!file.type.match(imageType)) {
  323. continue;
  324. }
  325.  
  326. /**
  327. * Create an image dom object dynamically
  328. */
  329. var img = document.createElement("img");
  330.  
  331. /**
  332. * Get preview area of the image
  333. */
  334. var preview = $(imageContainer).find('tr.imagePreviewRow_'+i).find('td:first');
  335.  
  336. /**
  337. * Append preview of selected image to the corresponding container
  338. */
  339. preview.append(img);
  340.  
  341. /**
  342. * Set style of appended preview(Can be done via css also)
  343. */
  344. preview.find('img').addClass('previewImage').css({'max-width': '500px', 'max-height': '500px'});
  345.  
  346. /**
  347. * Initialize file reader
  348. */
  349. var reader = new FileReader();
  350. /**
  351. * Onload event of file reader assign target image to the preview
  352. */
  353. reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
  354. /**
  355. * Initiate read
  356. */
  357. reader.readAsDataURL(file);
  358. }
  359. /**
  360. * Show preview
  361. */
  362. $(imageContainer).show();
  363. }
  364.  
  365. function remove_selected_image(close_button)
  366. {
  367. /**
  368. * Remove this image from preview
  369. */
  370. var imageIndex = $(close_button).attr('imageindex');
  371. $(close_button).parents('.imagePreviewRow_' + imageIndex).remove();
  372. }
  373.  
  374. function upload_images_selected(event, formObj)
  375. {
  376. event.preventDefault();
  377. //Get number of images
  378. var imageCount = $('.previewImage').length;
  379. //Get all multi select inputs
  380. var fileInputs = document.querySelectorAll('.multipleImageFileInput');
  381. //Url where the image is to be uploaded
  382. var url= "/upload-directory/";
  383. //Get number of inputs
  384. var number_of_inputs = $(fileInputs).length;
  385. var inputCount = 0;
  386.  
  387. //Iterate through each file selector input
  388. $(fileInputs).each(function(index, input){
  389.  
  390. fileList = input.files;
  391. // Create a new FormData object.
  392. var formData = new FormData();
  393. //Extra parameters can be added to the form data object
  394. formData.append('bulk_upload', '1');
  395. formData.append('username', $('input[name="username"]').val());
  396. //Iterate throug each images selected by each file selector and find if the image is present in the preview
  397. for (var i = 0; i < fileList.length; i++) {
  398. if ($(input).next('.imagePreviewTable').find('.imagePreviewRow_'+i).length != 0) {
  399. var file = fileList[i];
  400. // Check the file type.
  401. if (!file.type.match('image.*')) {
  402. continue;
  403. }
  404. // Add the file to the request.
  405. formData.append('image_uploader_multiple[' +(inputCount++)+ ']', file, file.name);
  406. }
  407. }
  408. // Set up the request.
  409. var xhr = new XMLHttpRequest();
  410. xhr.open('POST', url, true);
  411. xhr.onload = function () {
  412. if (xhr.status === 200) {
  413. var jsonResponse = JSON.parse(xhr.responseText);
  414. if (jsonResponse.status == 1) {
  415. $(jsonResponse.file_info).each(function(){
  416. //Iterate through response and find data corresponding to each file uploaded
  417. var uploaded_file_name = this.original;
  418. var saved_file_name = this.target;
  419. var file_name_input = '<input type="hidden" class="image_name" name="image_names[]" value="' +saved_file_name+ '" />';
  420. file_info_container.append(file_name_input);
  421.  
  422. imageCount--;
  423. })
  424. //Decrement count of inputs to find all images selected by all multi select are uploaded
  425. number_of_inputs--;
  426. if(number_of_inputs == 0) {
  427. //All images selected by each file selector is uploaded
  428. //Do necessary acteion post upload
  429. $('.overlay').hide();
  430. }
  431. } else {
  432. if (typeof jsonResponse.error_field_name != 'undefined') {
  433. //Do appropriate error action
  434. } else {
  435. alert(jsonResponse.message);
  436. }
  437. $('.overlay').hide();
  438. event.preventDefault();
  439. return false;
  440. }
  441. } else {
  442. /*alert('Something went wrong!');*/
  443. $('.overlay').hide();
  444. event.preventDefault();
  445. }
  446. };
  447. xhr.send(formData);
  448. })
  449.  
  450. return false;
  451. }
  452.  
  453. $(document).ready(function () {
  454. var options = {
  455. target: '#output', // target element(s) to be updated with server response
  456. timeout: 30000,
  457. error: function (jqXHR, textStatus) {
  458. $('#output').html('have any error');
  459. return false;
  460. }
  461. },
  462. success: afterSuccess, // post-submit callback
  463. resetForm: true
  464. // reset the form after successful submit
  465. };
  466.  
  467. $('#idOfInputFile').on('change', function () {
  468. $('#idOfForm').ajaxSubmit(options);
  469. // always return false to prevent standard browser submit and page navigation
  470. return false;
  471. });
  472. });
  473.  
  474. Javascript:
  475. var reader = new FileReader();
  476. reader.onloadend = function ()
  477. {
  478. dataToBeSent = reader.result.split("base64,")[1];
  479. $.post(url, {data:dataToBeSent});
  480. }
  481. reader.readAsDataURL(this.files[0]);
  482.  
  483.  
  484. PHP:
  485. file_put_contents('my.pdf', base64_decode($_POST["data"]));
  486.  
  487. <form action="" id="formContent" method="post" enctype="multipart/form-data" >
  488. <input type="file" name="file" required id="upload">
  489. <button class="submitI" >Upload Image</button>
  490. </form>
  491.  
  492. $("#formContent").submit(function(e){
  493. e.preventDefault();
  494.  
  495. var formdata = new FormData(this);
  496.  
  497. $.ajax({
  498. url: "ajax_upload_image.php",
  499. type: "POST",
  500. data: formdata,
  501. mimeTypes:"multipart/form-data",
  502. contentType: false,
  503. cache: false,
  504. processData: false,
  505. success: function(){
  506. alert("file successfully submitted");
  507. },error: function(){
  508. alert("okey");
  509. }
  510. });
  511. });
  512. });
  513.  
  514. $(document).ready(function() {
  515. var options = {
  516. beforeSubmit: showRequest,
  517. success: showResponse,
  518. dataType: 'json'
  519. };
  520. $('body').delegate('#image','change', function(){
  521. $('#upload').ajaxForm(options).submit();
  522. });
  523. });
  524. function showRequest(formData, jqForm, options) {
  525. $("#validation-errors").hide().empty();
  526. $("#output").css('display','none');
  527. return true;
  528. }
  529. function showResponse(response, statusText, xhr, $form) {
  530. if(response.success == false)
  531. {
  532. var arr = response.errors;
  533. $.each(arr, function(index, value)
  534. {
  535. if (value.length != 0)
  536. {
  537. $("#validation-errors").append('<div class="alert alert-error"><strong>'+ value +'</strong><div>');
  538. }
  539. });
  540. $("#validation-errors").show();
  541. } else {
  542. $("#output").html("<img src='"+response.file+"' />");
  543. $("#output").css('display','block');
  544. }
  545. }
  546.  
  547. <form class="form-horizontal" id="upload" enctype="multipart/form-data" method="post" action="upload/image'" autocomplete="off">
  548. <input type="file" name="image" id="image" />
  549. </form>
  550.  
  551. var formData = new FormData();
  552. formData.append("userfile", fileInputElement.files[0]);
  553.  
  554. data.append("myfile", myBlob, "filename.txt");
  555.  
  556. Have an iframe on page and have a referencer.
  557.  
  558. Form: A processing page AND a target of the FRAME.
  559.  
  560. data:image/png;base64,asdfasdfasdfasdfa
  561.  
  562. .aftersubmit(function(){
  563. stopPropigation()// or some other code which would prevent a refresh.
  564. });
  565.  
  566. var url = "YOUR_URL";
  567.  
  568. var form = $('#YOUR_FORM_ID')[0];
  569. var formData = new FormData(form);
  570.  
  571.  
  572. $.ajax(url, {
  573. method: 'post',
  574. processData: false,
  575. contentType: false,
  576. data: formData
  577. }).done(function(data){
  578. if (data.success){
  579. alert("Files uploaded");
  580. } else {
  581. alert("Error while uploading the files");
  582. }
  583. }).fail(function(data){
  584. console.log(data);
  585. alert("Error while uploading the files");
  586. });
  587.  
  588. <html>
  589. <head>
  590. <title>Ajax file upload</title>
  591. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  592. <script>
  593. $(document).ready(function (e) {
  594. $("#uploadimage").on('submit',(function(e) {
  595. e.preventDefault();
  596. $.ajax({
  597. url: "upload.php", // Url to which the request is send
  598. type: "POST", // Type of request to be send, called as method
  599. data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
  600. contentType: false, // The content type used when sending data to the server.
  601. cache: false, // To unable request pages to be cached
  602. processData:false, // To send DOMDocument or non processed data file it is set to false
  603. success: function(data) // A function to be called if request succeeds
  604. {
  605. alert(data);
  606. }
  607. });
  608. }));
  609.  
  610. </script>
  611. </head>
  612. <body>
  613. <div class="main">
  614. <h1>Ajax Image Upload</h1><br/>
  615. <hr>
  616. <form id="uploadimage" action="" method="post" enctype="multipart/form-data">
  617. <div id="image_preview"><img id="previewing" src="noimage.png" /></div>
  618. <hr id="line">
  619. <div id="selectImage">
  620. <label>Select Your Image</label><br/>
  621. <input type="file" name="file" id="file" required />
  622. <input type="submit" value="Upload" class="submit" />
  623. </div>
  624. </form>
  625. </div>
  626. </body>
  627. </html>
  628.  
  629. var dataform = new FormData($("#myform")[0]);
  630.  
  631. //console.log(dataform);
  632. $.ajax({
  633. url: 'url',
  634. type: 'POST',
  635. data: dataform,
  636. async: false,
  637. success: function (res) {
  638. response data;
  639. },
  640. cache: false,
  641. contentType: false,
  642. processData: false
  643. });
Add Comment
Please, Sign In to add comment