Write a relatively low file upload function. You need to click Upload to upload it to the server.
But after testing, it still fails to upload. I don’t know what’s going on? Below is my code:
html
<body>
<p class="toolbar1">
<a href="javascript:;" id="upload" class="a-upload mr10"><input id="changeFile" type="file" name="myFiles" id="">點(diǎn)擊這里上傳文件</a>
<p class="showFileName mr10"></p>
<button id="uploadBtn" type="button" class="btn btn-primary">上傳</button>
</p>
</body>
php:
<?php
//做個(gè)路由 action為url中的參數(shù)
$action = $_GET['action'];
switch($action) {
case 'upload_file':
upload();
break;
}
function upload(){
// 獲取上傳的圖片
$pic = $_FILES['myFiles']['tmp_name'];
$upload_ret = false;
if($pic){
// 上傳的路徑,建議寫物理路徑
$uploadDir = "../upload_files";
// 創(chuàng)建文件夾
if(!file_exists($uploadDir)){
mkdir($uploadDir, 0777);
}
// 用時(shí)間戳來(lái)保存圖片,防止重復(fù)
$targetFile = $uploadDir . '/' . time() . $_FILES['myFiles']['name'];
// 將臨時(shí)文件 移動(dòng)到我們指定的路徑,返回上傳結(jié)果
$upload_ret = move_uploaded_file($pic, $targetFile) ? true : false;
}
return $upload_ret;
}
?>
js:
$(function() {
//上傳圖片
$('#uploadBtn').on('click',function(){
/*alert('444');*/
uploadFiles();
})
function uploadFiles(){
//上傳文件接口
var uploadUrl = "./php/data.php?action=upload_file";
//選擇的文件
var files = document.getElementById('changeFile').files[0];
var fileArr = [files];
//經(jīng)過(guò)調(diào)試是不進(jìn)ajax的
$.ajax({
type:"post",
url:uploadUrl,
data:fileArr,
dataType: 'json',
contentType: 'application/json;charset=utf-8',
success: function(data) {
console.log(data);
},
error: function(data){
}
});
}
}
After debugging, ajax is not entered in js. I don’t know what is the problem? Please help, thank you!
In php, $pic = $_FILES['myFiles']['tmp_name'];
How to get the value of $pic? During debugging, I found that this value cannot be obtained. In js, I convert the obtained file information into an array and pass it through ajax post. How do I pass this array to php?
光陰似箭催人老,日月如移越少年。
You are passing mixed data, try changing contenttype and processData to false
$.ajax({
type:"post",
url:uploadUrl,
data:{ "yourfiles": files} //這里改成obj對(duì)象,
dataType: 'json',
contentType: false,
processData:false,
success: function(data) {
console.log(data);
},
error: function(data){
}
});
processData should be set to false
You need to use formData to submit using Ajax
var file = document.getElementById('changeFile').files[0]
var uploadUrl = "./php/data.php?action=upload_file"
var fd = new FormData()
fd.append('myFiles', file)
$.ajax({
type:"post",
url:uploadUrl,
data: fd,
processData: false,
contentType: false,
success: function(data) {
console.log(data);
},
error: function(data){
}
})