我尝试在php中使用ajax上传文件,花了一天时间才解决这个问题。我读了同样的问题并尝试使用它,但它确实没有用。 也许它可能会混乱,因为我试图将所有解决方案代码从堆栈溢出到我的代码。
它可能很长但是plz帮助我。谢谢T.Thtml part。
<form id="fileform" name="fileform" enctype="multipart/form-data">
<input id="fileinput" multiple="multiple" value="file" type="file" name="file">
<input id="file" type="submit" value="submit">
</form>
ajax part。
<script>
$(document).ready(function(){
$('form#fileform').submit(function(event){
event.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
type:"POST",
url:"io_update.php",
contentType: "application/json; charset=utf-8",
dataType:"JSON",
data: formData,
cache : false,
processData: false,
success:function(data){
// var success_text = '<div class="alert alert-success"><strong>Upload success.</strong> Here is the link to your file:</div>' +
// '<span class="lead"><a target="_blank" href="https://file.io/' + data + '">https://file.io/' + data + '</a><br /><br /></span>';
console.log("hh");
// console.log(data);
// $(this.getElementById("list")).html(success_text);
document.getElementById("list").innerHTML ='<div class="alert alert-success" style="font-size:10px; "><strong>Upload success.</strong> Here is the link to your file:</div>' +
'<span class="lead"><a target="_blank" href="' + data + '">' + data + '</a><br /><br /></span>';
// alert(data);
},error:function(request,status,error){
console.log("gg");
alert("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error);}
})
})
})
php part。
$file = json_decode($_POST['file']);
$folder="img/";
move_uploaded_file($file,$folder.$file);
function getimg($url) {
$headers[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg';
$headers[] = 'Connection: Keep-Alive';
$headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';
$user_agent = 'php';
$process = curl_init($url);
curl_setopt($process, CURLOPT_HTTPHEADER, $headers);
curl_setopt($process, CURLOPT_HEADER, 0);
curl_setopt($process, CURLOPT_USERAGENT, $user_agent); //check here
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);
$return = curl_exec($process);
curl_close($process);
return $return;
}
$imagename= basename($file);
$image = getimg($file);
file_put_contents('./img/'.$imagename,$image);
$sql1="INSERT INTO a_io(file) VALUES('$imagename')";
$result = mysqli_query($db,$sql1);
并且错误消息是 消息:
Notice: Undefined index: file in /home/hosting_users/kaist6123/www/io/io_update.php on line 45
Warning: file_put_contents(./img/): failed to open stream: Is a directory in /home/hosting_users/kaist6123/www/io/io_update.php on line 81
在我的数据库中,我在ajax之后取空文件。
答案 0 :(得分:0)
从你的ajax函数中删除它们
--debug
评论后更新
尝试替换以下行
contentType: "application/json; charset=utf-8",
dataType:"JSON",
带
$file = json_decode($_POST['file']);