没有提交按钮无法上传图片

没有提交按钮无法上传图片

本文介绍了没有提交按钮无法上传图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将mp3文件上传到服务器而不使用提交按钮,我正在使用ajax,但文件没有上传到服务器.我错了,这是我的代码

I am trying to upload mp3 file to server without using submit button i am using ajax but file not uploading to server.Where i am wrong here is my code

<script>
$(document).ready(function() {
    $('#fileToUpload').change(function(){
        var file_data = $('#fileToUpload').prop('files')[0];
        var form_data = new FormData();
        form_data.append('file', file_data);
        $.ajax({
            url: "modules/phone/newvoicemail.php",
            type: "POST",
            data: form_data,
            contentType: false,
            cache: false,
            processData:false,
            success: function(data){
                console.log(data);
            }
        });
    });
});
</script>

在newvoicemail.php中,我输入了以下代码

In newvoicemail.php i put following code

$src = $_FILES['file']['tmp_name'];
    $file_name = $_FILES['fileToUpload']['name'];
    $file_size =$_FILES['fileToUpload']['size'];
    $file_tmp =$_FILES['fileToUpload']['tmp_name'];
    $file_type=$_FILES['fileToUpload']['type'];
    move_uploaded_file($file_tmp,"voicemail/".$file_name);

这是我的html代码

<form name="voicemailform" action="modules/phone/voicemail.php" method="POST" enctype="multipart/form-data" class="form-inline for-frm">
<input type="file" name="fileToUpload" id="fileToUpload">
</form>

推荐答案

  1. 由于使用ajax上传,因此不需要nameaction,HTML form标记上的methodenctype属性.文件输入标签的name属性也是如此.

  1. Since you are uploading using ajax, you do not need name,action,method and enctype attributes on your HTML form tag. Same applies to name attribute of file input tag.

您需要在 $.ajax({...});

因为您要在JS中以参数名称 file 附加表单数据, form_data.append('file',file_data); ,您应该在php中访问它为 $ _ FILES ['file'] ,而不是

Since you are appending form data with param name file in JS asform_data.append('file', file_data);, you should access it in phpas $_FILES['file'] and not

HTML代码:

<form class="form-inline for-frm">
    <input type="file" id="fileToUpload">
</form>

JS代码:

       $('#fileToUpload').change(function () {
            var file_data = $('#fileToUpload').prop('files')[0];
            var form_data = new FormData();
            form_data.append('file', file_data);
            $.ajax({
                url: "modules/phone/newvoicemail.php",
                type: "POST",
                data: form_data,
                contentType: false,
                cache: false,
                enctype: 'multipart/form-data',
                processData: false,
                success: function (data) {
                    console.log(data);
                }
            });
        });

PHP代码:newvoicemail.php

<?php
    $src = $_FILES['file']['tmp_name'];
    $file_name = $_FILES['file']['name'];
    move_uploaded_file($src, "./voicemail/".$file_name);

这篇关于没有提交按钮无法上传图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 23:53