问题描述
我试图将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>
推荐答案
-
由于使用ajax上传,因此不需要
name
,action
,HTMLform
标记上的method
和enctype
属性.文件输入标签的name
属性也是如此.
Since you are uploading using ajax, you do not need
name
,action
,method
andenctype
attributes on your HTMLform
tag. Same applies toname
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);
这篇关于没有提交按钮无法上传图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!