weixin_33701617 2018-08-28 14:46 采纳率: 0%
浏览 13

使用AJAX jQuery上传文件

I'm trying to upload a single file with JQUERY AJAX. I found this old thread - Jquery ajax single file upload

I followed the codes, but I kept getting the "Not Set" error on my php script.

Here's my HTML

<form id="fileinfo" enctype="multipart/form-data" method="post" name="fileinfo">
    <label>File:</label>
    <input type="file" name="file" required />
</form>
<input type="button" id="upload" value="Upload"></input>
<div id="output"></div>

Here's my Jquery code. I used latest uncompressed CDN - https://code.jquery.com/jquery-3.3.1.js

$( document ).ready(function() {

    $('#upload').on('click', function(){ 

                var formData = new FormData(); 
                formData.append('file', $('input[type=file]')[0].files[0]);
        $.ajax({
            url: 'upload.php',  
            type: 'POST',
            data: formData,
            success:function(data){
                $('#output').html(data);
            },
            cache: false,
            contentType: false,
            processData: false
        });
    });
});

Here's my php script (upload.php)

<?php
    if(isset($_GET['file'])){
    $filename = $_FILES['file']['name'];
        if(isset($filename) && !empty($filename)){
        echo 'File available';
        }else{
        echo 'please choose a file';
        }
    } else{
    echo 'No file';
    }
?>

Update: Changed my PHP code with below and it fixed the issue.

<?php
$info = pathinfo($_FILES['file']['name']);
$ext = $info['extension']; // get the extension of the file
$newname = "newname.".$ext; 

$target = 'files/'.$newname;
move_uploaded_file( $_FILES['file']['tmp_name'], $target);

if (file_exists("files/{$newname}")) {
echo "Uploaded!";
}
?>
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 急matlab编程仿真二阶震荡系统
    • ¥20 TEC-9的数据通路实验
    • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
    • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
    • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
    • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
    • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
    • ¥15 python爬取bilibili校园招聘网站
    • ¥30 求解达问题(有红包)
    • ¥15 请解包一个pak文件