[英]How can I upload file with AJAX using PHP?
我想使用AJAX和PHP将文件上传到服务器。 到目前为止,这是我尝试过的方法,但不适用于我。 服务器引发此错误:-注意:未定义的索引:第3行的C:\\ xampp \\ htdocs \\ authentication \\ test.php中的文件注意:未定义的索引:第C行的C:\\ xampp \\ htdocs \\ authentication \\ test.php中的文件7注意:未定义的索引:第7行上C:\\ xampp \\ htdocs \\ authentication \\ test.php中的文件:客户端代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Form Generator</title> <link rel="stylesheet" type="text/css" href="style.css" /> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script> <script type="text/javascript" src="jquery-2.1.4.js"></script> <script type="text/javascript"> function valid(){ var file_data = $('#sortpicture').prop('files')[0]; var form_data = new FormData(); form_data.append('file', file_data); alert(form_data); $.ajax({ url: 'test.php', // point to server-side PHP script dataType: 'text', // what to expect back from the PHP script, if anything cache: false, contentType: false, processData: false, data: form_data, type: 'post', success: function(data){ $('#result').html(data); // display response from the PHP script, if any } }); } </script> </head> <body> <div id='result'></div> <input id="sortpicture" type="file" name="sortpic" /> <button id="upload" onclick='valid()'>Upload</button> </body> </html>
这是客户端代码test.php:
<?php if ( 0 < $_FILES['file']['error'] ) { echo 'Error: ' . $_FILES['file']['error'] . '<br>'; } else { if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name'])){ echo "file uploaded"; } } ?>
使用jQuery File Upload
Plugin,它具有许多很酷的功能,可以节省更多时间并避免再次发明轮子。
图书馆:
https://blueimp.github.io/jQuery-File-Upload/
PHP安装指南: https : //github.com/blueimp/jQuery-File-Upload/wiki/Setup
$(function () {
'use strict';
// Initialize the jQuery File Upload widget:
$('#fileupload').fileupload({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: 'server/php/'
});
// Enable iframe cross-domain access via redirect option:
$('#fileupload').fileupload(
'option',
'redirect',
window.location.href.replace(
/\/[^\/]*$/,
'/cors/result.html?%s'
)
);
if (window.location.hostname === 'blueimp.github.io') {
// Demo settings:
$('#fileupload').fileupload('option', {
url: '//jquery-file-upload.appspot.com/',
// Enable image resizing, except for Android and Opera,
// which actually support image resizing, but fail to
// send Blob objects via XHR requests:
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator.userAgent),
maxFileSize: 999000,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i
});
// Upload server status check for browsers with CORS support:
if ($.support.cors) {
$.ajax({
url: '//jquery-file-upload.appspot.com/',
type: 'HEAD'
}).fail(function () {
$('<div class="alert alert-danger"/>')
.text('Upload server currently unavailable - ' +
new Date())
.appendTo('#fileupload');
});
}
} else {
// Load existing files:
$('#fileupload').addClass('fileupload-processing');
$.ajax({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: $('#fileupload').fileupload('option', 'url'),
dataType: 'json',
context: $('#fileupload')[0]
}).always(function () {
$(this).removeClass('fileupload-processing');
}).done(function (result) {
$(this).fileupload('option', 'done')
.call(this, $.Event('done'), {result: result});
});
}
});
这两行是错误的:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery-2.1.4.js"></script>
仅使用jQuery的一个版本:1.5.1或2.1.4(我建议使用最后一个)!
错误消息告诉您,PHP中的$ _FILES关联数组没有'file'成员。 我想你要“名字”。
这始终对我有效:
function valid(){
var formData = new FormData();
formData.append('file', $("#sortpicture")[0].files[0]);
$.ajax({
url: "test.php",
type: 'POST',
dataType: 'json',
processData: false,
contentType: false,
data: formData,
success: function(data){
// Process response here. May be preview image?
},
error: function(r){
// Handle errors
},
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.