Good day!

I have such a problem - I am going to upload pictures to the site without reloading the page via ajax.

There is such a form:

<form name="uploadimages" method="post" enctype="multipart/form-data"> <input id="uploadimage" type="FILE" name="uploadimage" id="uploadfile"> </form> 

and this is the function that should send the Ajax file from the download field to the handler like this:

  <script type="text/javascript"> function setimage() { var uploadfile = $("#uploadimage").val(); $.ajax({ type: "POST", url: "uploadimages.php", data: "img=" + uploadfile, success: function(html){ $("#textar").append(html); } }); } </script> 

There are no problems with this, everything works in the handler, except for one thing - there is a resize function that works separately too!
It looks like this:

 //тут объявляется функция $img = $_POST['img'];//получаем данные $image = imageResize($img, 'litimages', 1000, 1000);//делаем ресайз (пареметры - картнка, директория для сохраненияя, размеры) $image = "<br><br><img src='".$image."' width='700'><br><br>"; //вставляем в тег адрес echo $image; //и возвращаем 

Everything is logical, but in fact gives an error:

Catchable fatal error: Argument 1 passed to imageResize () must be an array of string, given, called in Z: \ home \ superli \ www \ uploadimages.php on line 92 and defined in Z: \ home \ superli \ www \ uploadimages. php on line 5

This, as for me, is related to the fact that here

 var uploadfile = $("#uploadimage").val(); 

The name of the picture is sent, and not the picture itself.

Please help me figure out how to properly send the file itself, thanks in advance!

  • stackoverflow.com/questions/6974684/… - this is what a proper file load looks like through jQuery. imageResize - most likely waiting for an array of the file (from $_FILES['img'] ), although here I could be wrong. - RubaXa
  • Yes, that is what he expects. (I read that you should use formdata () to send, but I didn’t figure out how it works properly. - dantelol
  • Here var uploadfile = $ ("# uploadimage"). Val (); You send a string which stores the path to the file. And the server itself does not understand this way. You do not need to send the path, but the data itself. - MarinaVoyin
  • Something @RubaXa concealed or was too lazy to tell more)) But [he has on github] [1] even has a job on this topic. [1]: rubaxa.imtqy.com/jquery.fileapi - Deonis
  • so then? but I didn’t get it, it doesn’t work (var uploadfile = new FormData (); uploadfile.append ('uploadimage', input.files [0]); - dantelol

2 answers 2

The question is about jQuery, and not how to download files for all browsers. It's simple, look ( jsfiddle ):

 function setimage() { var $input = $("#uploadimage"); var fd = new FormData; fd.append('img', $input.prop('files')[0]); $.ajax({ url: 'http://example.com/script.php', data: fd, processData: false, contentType: false, type: 'POST', success: function (data) { alert(data); } }); } 

Update

Oh, ho, php has nothing to do with it, the dollar at the beginning of the variable name means that it most likely contains a jQuery collection.

Update

Did you change your script? But not in the example you have $_POST['img'] , but there should be $_FILES['img'] about which I wrote above. It seems to me too early for you to deal with such things, start with the basics of php, learn how to download a file without ajax, and then try to tie it to the working code.

  • Catchable fatal error: Argument 1 passed to imageResize () must be an array, it will be called in z: \ home \ superli \ www \ uploadimages.php 90 and defined in Z: \ home \ superli \ www \ uploadimages. php on line 4 - dantelol
  • thanks) this was the case) in pkhp I’m doing a multi-boot without any problems - I’m just getting my eyes on my eyes getting confused everything is time to go) and so the problem is solved! Thank you all, I will mark this answer correct) - dantelol

Loading a lot of photos with preservation of those names of photos that have already been uploaded (this is useful if you need to add them to the database, since you can download 200 photos at once, 5 for each lap):

HTML code:

 <form id='loadPhform' action='index.php' method='POST' enctype = 'multipart/form-data'> <input id='thisPh' type='file' name='insPh' multiple><br/> </form> 

Javascript code:

 //This Virables Is Globals (Объявляем переменные) window.Arr = []; window.el = $; window.LengthImg = 0; window.VirableLoading = 0; //Download Pictures (Загрузка изображений) $('#thisPh').on('change', function() { //Create Object FormData (Создание объекта типа form) var formData = new FormData(); //Если выбранные изображение больше 5 if($('#thisPh')[0].files.length > 5) return false; //Insert File Listes In An Object FormData (Создание вставки массивов изображений $_FILES в объект formdata ) $.each($('#thisPh')[0].files, function(count, This_File) { //If MIME Type Of Picture Not Match With That Formats (Если не соответствует тип) if(!This_File.type.match(/(.png)|(.jpeg)|(.jpg)|(.gif)$/i) || ($('#thisPh')[0].files[count].size / 1024).toFixed(0) > 1524) return false; //Иначе else { //Append Objects ( вставляем массивы изображений $_FILES в объект formdata ) formData.append("image" + count, This_File); //Если мы уже вставили все изображения if(count == $('#thisPh')[0].files.length - 1) { var query = 0; //Вторая защита (если имя НЕ неизвестно) if($("#thisPh")[0].files[0].name != undefined){ //Query $.ajax({ url: 'ajaxDocs/DownloadAlbumPhotos.php', type: 'POST', contentType: false, processData: false, dataType: 'json', data: formData, beforeSend: function(loading) { $('.loading').css("display", "block"); }, success: function(data) { if(data['state'] == "success") { VirableLoading++; $('.loading').css("display", "none"); //Cycle for(var i = 0; i < data['lengthArr'] + 1; i++) { //Loading More Photos Arr[LengthImg + i] = data['srcPart'][i]; //If the cycle is ended if(i == data['lengthArr']) { //Length Photos LengthImg += data['lengthArr'] + 1; //How Much Pictures Downloaded $('#DownloadedPics').val("Загружено (" + LengthImg + ")"); } } } } }); } } } }); }); 

php code:

 <?php $Array = array(); $count = -1; //Upload Files foreach($_FILES as $Pictures) { $count++; /***Здесь происходит загрузка изображений (можно и в базу вместе)***/ //Здесь накапливается массив с путями изображений (чтобы например вывести эти все фотки) $Array[$count] = $namePic; } //Здесь мы через JSON в элементе [srcPart] отправляем массив путей изображений , в элементе // [lengthArr] сколько изображений , в элемение [state] состояние $json_data = array ('srcPart' => $Array, 'lengthArr' => $count, 'state' => "success"); echo json_encode($json_data); ?> 
  • Thank you - I’ll save this code) but for now I’ll understand how to get a file as a newbie) - dantelol
  • and there before input exactly the dollar should stand in php variable? or is it wrong? var $ input = $ ("# uploadimage"); var fd = new FormData; fd.append ('img', $ input.prop ('files') [0]); $ .ajax ({url: 'uploadimages.php', data: fd, processData: false, contentType: false, type: 'POST', success: function (data) {alert (data);}}); - dantelol
  • vobshchem here @RubaXa gave the correct answer everything works speak someone who that is true! - dantelol