I try to delete the image from the preview, it is cleaned in the class, but the example gets to the server

function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function(e) { $('#image').attr('src', e.target.result); }; reader.readAsDataURL(input.files[0]); } } $("#photo").change(function() { readURL(this); }); $('#delete').click(function() { $('#image').remove(); // Удаляем превью }); $("#multiform").submit(function(e) { var formObj = $(this); var formURL = formObj.attr("action"); if (window.FormData !== undefined) // for HTML5 browsers { var formData = new FormData(this); $.ajax({ url: formURL, type: "POST", data: formData, mimeType: "multipart/form-data", contentType: false, cache: false, processData: false, success: function(data, textStatus, jqXHR) { alert('rtrth'); }, error: function(jqXHR, textStatus, errorThrown) { alert('1111'); } }); e.preventDefault(); } }); 
 .input-file-row-1:after { content: "."; display: block; clear: both; visibility: hidden; line-height: 0; height: 0; } .input-file-row-1 { display: inline-block; margin-top: 25px; position: relative; } html[xmlns] .input-file-row-1 { display: block; } * html .input-file-row-1 { height: 1%; } .upload-file-container { position: relative; width: 100px; height: 137px; overflow: hidden; background: url(http://i.imgur.com/AeUEdJb.png) top center no-repeat; float: left; margin-left: 23px; } .upload-file-container:first-child { margin-left: 0; } .upload-file-container > img { width: 93px; height: 93px; border-radius: 5px; -webkit-border-radius: 5px; -moz-border-radius: 5px; } .upload-file-container-text { font-family: Arial, sans-serif; font-size: 12px; color: #719d2b; line-height: 17px; text-align: center; display: block; position: absolute; left: 0; bottom: 0; width: 100px; height: 35px; } .upload-file-container-text > span { border-bottom: 1px solid #719d2b; cursor: pointer; } .upload-file-container input { position: absolute; left: 0; bottom: 0; font-size: 1px; opacity: 0; filter: alpha(opacity=0); margin: 0; padding: 0; border: none; width: 70px; height: 50px; cursor: pointer; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form name="multiform" id="multiform" action="multi-form-submit.php" method="POST" enctype="multipart/form-data"> Name: <input type="text" name="name" value="" /> <br/>Age : <input type="text" name="age" value="" /> <br/>Image : <input type="file" id="photo" class="photo" name="photo" /> <br/> <button class="btn btn-info" id="multi-post">Run Code</button> </form> <img id="image" src="#" alt="" /> <div id="delete">delete</div> 

  • It is not clear that it does not work. In the snippet, the picture loads and changes correctly. - Denis Matafonov
  • asked the developer of the plug-in, and as I understood that the plug-in needed to be rewritten, this doesn’t work. Suppose you have the ad serving form and you need the form to work if the text is in the input and the picture is not loaded for some reason or another - Koly
  • need not ship kratinku ??? - L. Vadim
  • Yes, in one case a person will upload a picture in another not - Koly

1 answer 1

The mistake is that deleting a preview, you do not delete the form data.

To delete correctly, you need to clone for example the input where the picture is inserted:

 $('#delete').click(function() { $('#image').remove(); // Удаляем превью //Заменяем инпут на чистый (без картинки) клонированием $('#photo').replaceWith($('#photo').clone()); //Или вот так можно почистить $('#photo').get(0).reset(); }); 

Among other things, I do not see much point in using FormData in this case; You can send a regular variable to the server - in this case, the code is much simpler and clearer.

 $('#photo').on('change', function(event){ var $this = $(this); $this.replaceWith($this.clone()); //Сразу чистим инпут var file_name = $(this).attr('name'); //Прямо на инпуте можно задать имя файла var reader = new FileReader(); var f = event.target.files[0], nameArr = event.target.files[0]['name'].split('.'), extension = nameArr[nameArr.length-1].toLowerCase(); //Проверяем какие расширения файла разрешены var allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'pdf']; if (allowedExtensions.indexOf(extension) == -1) { return alert('Недопустимое расширение файла'); } reader.onload = function(e) { var contents = e.target.result; contents = contents.split('base64,')[1]; //на сервер не нужно отправлять начало содержимого sendFileAsBinary(file_name, extension, contents); }; reader.readAsDataURL(f); }) //Функция отправки файла function sendFileAsBinary(file_name, extension, img) { $.ajax({ xhr: function() { var xhr = new window.XMLHttpRequest(); xhr.upload.addEventListener("progress", function(evt) { if (evt.lengthComputable) { var percentComplete = evt.loaded / evt.total; percentComplete = parseInt(percentComplete * 100); //Процент загрузки можно отобразить if (percentComplete === 100) { //Закончили загрузку } } }, false); return xhr; }, url: '/ссылка', type: 'POST', data: { name: file_name, //название файла img: img, //это бинарный текст файла extension: extension //это его расширение чтобы на сервере создать нужный файл }, dataType: 'json', success: function(data){ //Успешно отправили }, complete: function(data) { //Сюда нужно вставлять функции по завершении загрузки - оно сработает позднее чем success } }) } 
  • Thanks, I just decided to try to cut down my crutch, learn a little, but thanks again - Koly
  • the most important thing to understand here is that Filereader returns a text string, the contents of any graphic (in this case) with the word base54 glued in front. You cut off the word - you get the real contents of the file, which you can stupidly save to a file with the desired extension and you get a picture. So all plugins in the firebox are just the contents of a file that you can send to the server as your heart desires. - Denis Matafonov