【发布时间】:2014-11-06 02:26:47
【问题描述】:
我想使用 ajax 和 json 上传文件。 PHP 文件有一个多部分的形式。我想传递一个文件oo我的js文件并使用ajax和json将文件传递给我的上传文件。我唯一有问题的代码部分是专辑封面,它是一个文件。以下适用于所有输入的文本,但不知道如何上传文件。
文件的 id 称为专辑封面。
<form action="" method="post" name="artist_create_song_album" id="artist_create_song_album" class="smart-form client-form" enctype="multipart/form-data">
<input type="file" name="album_cover" id="album_cover" placeholder="Album Cover">
下面的JS文件被调用。
runAllForms();
$(function () {
$("#artist_create_song_album").validate({
rules: {
album_cover: {
required: true
},
song_album_name: {
required: true
},
song_album_description: {
required: true
}
},
// messages for form validation
messages: {
album_cover: {
required: 'Please upload album cover'
},
song_album_name: {
required: 'Please enter album name'
},
song_album_description: {
required: 'Please enter album description'
}
},
errorPlacement: function (error, element) {
error.insertAfter(element.parent());
},
submitHandler: function () {
$('#artist_create_song_album').hide(0);
$('#art_song_message').hide(0);
$.ajax({
url: 'artist_update_songs.php',
type: 'POST',
dataType: 'json',
data: {
album_cover: $('#album_cover').val(),
song_album_name: $('#song_album_name').val(),
song_album_description: $('#song_album_description').val()
},
success: function (data) {
$('#art_song_message').removeClass().addClass((data.error === true) ? 'error' : 'success')
.text(data.msg).show(500);
if (data.error === true) {
if (data.goto == 1) {
window.location = "http://dev.worldmusicstage.com/main.php#/ajax/artist_dashboard_info.php";
$('#artist_create_song_album').show(500);
delete json;
} else {
$('#artist_create_song_album').show(500);
}
}
if (data.error === false) {
window.location = "http://dev.worldmusicstage.com/main.php#/ajax/artist_dashboard_info.php";
$('#artist_create_song_album').show(500);
delete json;
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$('#art_song_message').removeClass().addClass('error')
alert('The error was: ' + errorThrown);
alert('The error was: ' + XMLHttpRequest);
alert('The error was: ' + textStatus);
alert(errorThrown.stack)
$('#artist_create_song_album').show(500);
}
});
return false;
}
});
});
【问题讨论】:
-
dropzonejs.com 也是上传文件而无需页面回发的好选择。
-
我在网站上有 dropzone,但由于某种原因,我只能使用两个 dropzone 实例。如果我添加第三个实例,它就不起作用。不太清楚那里发生了什么。
标签: jquery ajax json upload blob