我可以将图像表单数据传递给PHP函数进行上传吗?
我正在尝试使用jquery和PHP来上传这样的图像:
HTML
当前的jquery框架如下所示:
$('#photo-img').change(function(){ var file = this.files[0]; //console.log(file); name = file.name; size = file.size; type = file.type; // I'll do some validation here before proceeding var formData = new FormData($('#form-photo')); console.log(formData); // How do I pass the image form data to a PHP function via jquery? });
我可以通过jquery post将formData传递给PHP函数吗?
测试并使用Goolge Chrome
, Opera
, Firefox
, Safari
。
doesn't work with IE8 or lower
使用Javascript
创建一个FormData
对象并使用索引photo-img
附加该file
,并在XMLHttpRequest
的帮助下将其POST
到您的服务器
$(function() { $('#photo-img').change(function(){ var file = this.files[0]; // do your validation here var formData = new FormData(); formData.append( 'photo-img', file ); // append the file to form data var xhr = false; if ( typeof XMLHttpRequest !== 'undefined' ) { xhr = new XMLHttpRequest(); } else { var versions = [ "MSXML2.XmlHttp.5.0", "MSXML2.XmlHttp.4.0", "MSXML2.XmlHttp.3.0", "MSXML2.XmlHttp.2.0", "Microsoft.XmlHttp" ]; for( var i = 0, len = versions.length; i < len; i++ ) { try { xhr = new ActiveXObject( versions[i] ); break; } catch(e) {} } } if ( xhr ) { // replace test.php with your own upload script url xhr.open( "POST", "test.php", true ); xhr.onreadystatechange = function() { if ( this.readyState === 4 && this.status == 200 ) { var response = this.response || this.responseText; /** Do Something with the reponse **/ response = $.parseJSON( response ); if ( response && response.message ) { window.alert( response.message ); } } } // now send the formData to server xhr.send( formData ); } }); });
PHP
在服务器端更好的图像上载处理并返回JSON
对象作为响应
upload_max_filesize directive in php.ini'; break; case UPLOAD_ERR_FORM_SIZE: $error = 'Error '.$code.': The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form'; break; case UPLOAD_ERR_PARTIAL: $error = 'Error '.$code.': The uploaded file was only partially uploaded'; break; case UPLOAD_ERR_NO_FILE: $error = 'Error '.$code.': No file was uploaded'; break; case UPLOAD_ERR_NO_TMP_DIR: $error = 'Error '.$code.': Missing a temporary folder'; break; case UPLOAD_ERR_CANT_WRITE: $error = 'Error '.$code.': Failed to write file to disk'; break; case UPLOAD_ERR_EXTENSION: $error = 'Error '.$code.': A PHP extension stopped the file upload'; break; default: $error = 'Error '.$code.': Unknown upload error'; break; } } else { $iminfo = @getimagesize( $image["tmp_name"] ); if ( $iminfo && is_array( $iminfo ) ) { if ( isset( $iminfo[2] ) && in_array( $iminfo[2], $valid ) && is_readable( $image["tmp_name"] ) ) { if ( !move_uploaded_file( $image["tmp_name"], $target ) ) { $error = "Error while moving uploaded file"; } } else { $error = "Invalid format or image is not readable"; } } else { $error = "Only image files are allowed (jpg, gif, png)"; } } if ( empty( $error ) ) { echo json_encode( array( "error" => 0, "message" => "Upload success!" ) ); } else { echo json_encode( array( "error" => 1, "message" => $error ) ); } exit(); } ?>
您可以在jquery中使用$ .ajax方法并将表单数据发送到php文件。
$.ajax({ type: "POST", url: "http://localhost/index.php", data: data, success: success, });
请注意,$ .post和$ .ajax非常相似(默认情况下除$ .ajax使用type = get,您必须将其更改为type = post)。 您可以使用$ .ajax更好地控制内容,但$ .post更流线型 – 将$ .post视为执行AJAX POST的简便方法。 但是,因为$ .ajax通常比$ .post更具结构性,所以对于那些刚接触AJAX的人来说,尝试添加修饰符是很好的方法,例如dataType:JSON
, contentType
,甚至是async:false
。
Ajax代码是这样的:
$('#photo-img').change(function(){ var file = this.files[0]; //console.log(file); name = file.name; size = file.size; type = file.type; $.ajax({ type: "POST", url: "your_php_file.php", data: 'f_name=' +name+ '&f_size=' +size+ '&f_type=' +type, success: function(whatigot) { alert('Server-side response: ' + whatigot); } //END success fn }); //END $.ajax }); //END dropdown change event
请注意,从PHP文件返回的任何数据都会在AJAX调用的成功函数中进入HTML文档,并且必须在那里处理。 这就是您将接收到的数据插入DOM的位置。
例如,假设您的HTML文档具有id="myDiv"
的DIV。 要将PHP中的数据插入到HTML文档中,请替换line: alert('Server-side response: ' + whatigot);
有了这个:
$('#myDiv').html(whatIgot);
您的DIV现在包含从PHP文件回显的数据。
在PHP方面,它基本上是这样的:
'; $r .= ' - File Name: ' .$file_name.'
- File Size: ' .$file_size.'
- File Type: ' .$file_type.'
'; echo $r;
请参阅此示例 ,了解其工作原理。
请注意,上面的示例使用jQuery,因此在页面的标记中需要此引用: