javascript - jQuery AJAX file upload PHP -
i want implement simple file upload in intranet-page, smallest setup possible.
this html part:
<input id="sortpicture" type="file" name="sortpic" /> <button id="upload">upload</button>
and js jquery script:
$("#upload").on("click", function() { var file_data = $("#sortpicture").prop("files")[0]; var form_data = new formdata(); form_data.append("file", file_data) alert(form_data); $.ajax({ url: "/uploads", datatype: 'script', cache: false, contenttype: false, processdata: false, data: form_data, type: 'post', success: function(){ alert("works"); } }); });
there folder named "uploads" in root directory of website, change permissions "users" , "iis_users".
when select file file-form , press upload button, first alert returns "[object formdata]". second alert doesn't called , the"uploads" folder empty too!?
can finding out whats wrong?
also next step should be, rename file server side generated name. maybe can give me solution this, too.
you need script runs on server move file uploads directory. jquery ajax
method (running in browser) sends form data server, script on server handles upload. here's example using php.
your html fine, update js jquery script this:
$('#upload').on('click', function() { var file_data = $('#sortpicture').prop('files')[0]; var form_data = new formdata(); form_data.append('file', file_data); alert(form_data); $.ajax({ url: 'upload.php', // point server-side php script datatype: 'text', // expect php script, if cache: false, contenttype: false, processdata: false, data: form_data, type: 'post', success: function(php_script_response){ alert(php_script_response); // display response php script, if } }); });
and server-side script, using php in case.
upload.php: php script runs on server , directs file uploads directory:
<?php if ( 0 < $_files['file']['error'] ) { echo 'error: ' . $_files['file']['error'] . '<br>'; } else { move_uploaded_file($_files['file']['tmp_name'], 'uploads/' . $_files['file']['name']); } ?>
also, couple things destination directory:
- make sure have correct server path, i.e., starting @ php script location path uploads directory, and
- make sure it's writeable.
and little bit php function move_uploaded_file
, used in upload.php script:
move_uploaded_file( // file temporarily stored on server when uploaded // not change $_files['file']['tmp_name'], // want put file , want name // in case putting in directory called "uploads" // , giving original filename 'uploads/' . $_files['file']['name'] );
$_files['file']['name']
name of file uploaded. don't have use that. can give file name (server filesystem compatible) want:
move_uploaded_file( $_files['file']['tmp_name'], 'uploads/my_new_filename.whatever' );
and finally, aware of php upload_max_filesize
, post_max_size
configuration values, , sure test files not exceed either. here's how check php configuration , how set max filesize , post settings.
Comments
Post a Comment