简体   繁体   English

上载图片而不提交表单

[英]Uploading an image without form submitting

<input type='file' name='inputfile' id='inputfile'>

I'm trying to upload an image without a form submitting - just after input file is changed: 我正在尝试在不提交表单的情况下上传图像-更改输入file后:

$('#inputfile').change(function(){
    $.ajax({
        url: "pro-img-disk.php",
        type: "POST",
        data:  new FormData('#inpufile'),
        contentType: false,
        cache: false,
        processData:false,
        success: function(data){
            console.log(data);
        }
    });
});

PHP 的PHP

$src = $_FILES['inputfile']['tmp_name'];
$targ = "../images/".$_FILES['inputfile']['name'];
move_uploaded_file($src, $targ);

Error: 错误:
Undefined index: inputfile...

Any help? 有什么帮助吗?

See to the following changes: 请参阅以下更改:

<input type='file' name='inputfile' id='inputfile'>

Here's how you should have sent the ajax request: 这是您应该如何发送ajax请求的方法:

$(document).ready(function() {
    $('#inputfile').change(function(){
        var file_data = $('#inputfile').prop('files')[0];   
        var form_data = new FormData();                  
        form_data.append('file', file_data);
        $.ajax({
            url: "pro-img-disk.php",
            type: "POST",
            data: form_data,
            contentType: false,
            cache: false,
            processData:false,
            success: function(data){
                console.log(data);
            }
        });
    });
});

And lastly, here's how you should have processed the form data: 最后,这是您应该如何处理表单数据的方法:

$src = $_FILES['file']['tmp_name'];
$targ = "../images/".$_FILES['file']['name'];
move_uploaded_file($src, $targ);

Try this: 尝试这个:

var file_data = $('#inputfile').prop('files')[0];
var form_data = new FormData();                     // Create a form
form_data.append('inputfile', file_data);           // append file to form

$.ajax({
        url: "pro-img-disk.php",
        type        : 'post',
        cache       : false,
        contentType : false,
        processData : false,
        data        : form_data,                         
        success     : function(response){
            alert(response);
        }
 });

in php you can get the file data like: 在PHP中,您可以获取文件数据,例如:

$_FILES['inputfile']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM