jQueryAjax文件上传PHP我想实现一个简单的文件上传在我的内联网页面,与最小的设置可能。这是我的HTML部分:<input id="sortpicture" type="file" name="sortpic" /><button id="upload">Upload</button>这是我的JS jQuery脚本:$("#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");
}
});});该网站的根目录中有一个名为“上载”的文件夹,其中包含“用户”和“IIS_USERS”的更改权限。当我选择带有文件表单的文件并按下Upload按钮时,第一个警报返回“[ObjectFormData]”。第二个警报没有被调用,并且“上传”文件夹也是空的!?有人能帮我找出什么不对劲吗?另外,下一步应该是用服务器端生成的名称重命名文件。也许有人也能给我一个解决办法。
4 回答
翻过高山走不出你
TA贡献1875条经验 获得超3个赞
ajax
$('#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 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(php_script_response){ alert(php_script_response); // display response from the PHP script, if any } });});
upad.php
<?php if ( 0 < $_FILES['file']['error'] ) { echo 'Error: ' . $_FILES['file']['error'] . '<br>'; } else { move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']); }?>
确保你有 正确的服务器路径
,即从PHP脚本位置开始,上传目录的路径是什么,以及 确保它是 可写.
move_uploaded_file
move_uploaded_file( // this is where the file is temporarily stored on the server when uploaded // do not change this $_FILES['file']['tmp_name'], // this is where you want to put the file and what you want to name it // in this case we are putting in a directory called "uploads" // and giving it the original filename 'uploads/' . $_FILES['file']['name']);
$_FILES['file']['name']
move_uploaded_file( $_FILES['file']['tmp_name'], 'uploads/my_new_filename.whatever');
upload_max_filesize
post_max_size
幕布斯6054654
TA贡献1876条经验 获得超7个赞
var formData = new FormData($("#YOUR_FORM_ID")[0]);$.ajax({ url: "upload.php", type: "POST", data : formData, processData: false, contentType: false, beforeSend: function() { }, success: function(data){ }, error: function(xhr, ajaxOptions, thrownError) { console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); }});
浮云间
TA贡献1829条经验 获得超4个赞
<?$data = array(); //check with your logic if (isset($_FILES)) { $error = false; $files = array(); $uploaddir = $target_dir; foreach ($_FILES as $file) { if (move_uploaded_file($file['tmp_name'], $uploaddir . basename( $file['name']))) { $files[] = $uploaddir . $file['name']; } else { $error = true; } } $data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files); } else { $data = array('success' => 'NO FILES ARE SENT','formData' => $_REQUEST); } echo json_encode($data);?>
添加回答
举报
0/150
提交
取消